如何使TypeScript与SystemJS一起使用? (带有.js扩展名的问题)

问题描述 投票:4回答:3

我从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,我仍然遇到相同的问题。

typescript systemjs typescript1.7
3个回答
1
投票

我认为您的问题是模块名称中缺少js扩展名。不久前,System.js进行了更改,现在无需显式指定“ .js”就可以解决它们,您必须像这样在index.html中设置System.js选项:

System.defaultJSExtensions = true;

有关更多信息:defaultJSExtensions

编辑

正如@Naresh指出的那样,defaultJSExtensions现在已过时。现在看来,最好的方法是在配置中使用packages选项。

希望这会有所帮助。


0
投票

在您的tsconfig中:

“模块”:“ commonjs”,

由于您正在使用systemjs,因此将模块格式更改为system


0
投票

在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,但它显示了如何控制配置。

© www.soinside.com 2019 - 2024. All rights reserved.