我从TypeScript文件中的以下导入开始。请注意,没有.ts扩展名表示我正在导入TypeScript模块:
import githubService from './github.service';
这被翻译为:
var github_service_1 = require('./github.service');
[SystemJS尝试加载此模块时,它发出以下HTTP命令:
GET /github.service
而不是GET /github.service.js
。这显然不起作用。
如何使TypeScript与SystemJS一起使用?
这是我的tsconfig.json文件:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"outDir": "./dist",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true
},
"exclude": [
"node_modules"
],
"compileOnSave": false
}
我还尝试将上面的module
选项更改为system
(将生成的模块格式从CommonJS更改为SystemJS,我仍然遇到相同的问题。
我认为您的问题是模块名称中缺少js扩展名。不久前,System.js进行了更改,现在无需显式指定“ .js”就可以解决它们,您必须像这样在index.html中设置System.js选项:
System.defaultJSExtensions = true;
有关更多信息:defaultJSExtensions
编辑
正如@Naresh指出的那样,defaultJSExtensions现在已过时。现在看来,最好的方法是在配置中使用packages选项。
希望这会有所帮助。
在您的tsconfig中:
“模块”:“ commonjs”,
由于您正在使用systemjs,因此将模块格式更改为system
。
在System 2.0+中,您可以使用Loader Hooks
自定义内容
https://github.com/systemjs/systemjs/blob/2.0.0/docs/hooks.md#loader-hooks
例如,要在解析模块时将.js文件扩展名添加到模块,您可以覆盖System.prototype.resolve
函数:
const origResolve = System.constructor.prototype.resolve
System.constructor.prototype.resolve = function(moduleId, ...args) {
return origResolve.call(
this,
moduleId + '.js', // add .js extension to original module id
...args
)
}
请注意,这是一个非常幼稚的示例,因为您可能不想在每个模块ID中添加.js,但它显示了如何控制配置。