带有 TypeScript 的 SystemJs 简单示例失败



我正在尝试将SystemJs与TypeScript一起使用,基于这篇文章:http://david-barreto.com/how-to-use-typescript-with-systemjs/

索引.html

<!DOCTYPE html>
<script src="node_modules/systemjs/dist/system.js"></script>
<script src="node_modules/typescript/lib/typescript.js"></script>
<script>
  System.config({
    transpiler: 'typescript'
  });
  System.import('src/main.ts');
</script>

主目录

function plusOne(num: number) {
  return num+1;
}
alert(plusOne(1))

但是,在 Chrome 中.html oppen 索引时,我看到以下错误,指示没有发生转译:

common.js:85 Uncaught (in promise) Error: Unexpected token :
  Evaluating http://localhost:8080/src/main.ts
  Loading src/main.ts
    ...

问题出在哪里?

发生错误是因为 SystemJS 不使用打字稿来转译 main.ts 中的源代码,因为它没有检测到代码需要转译 - 它不包含 es6 功能,如 SystemJS 检查的exportimport

这就是transpiler选项的工作方式。您想设置transpiler: 'typescript'以将其用于打字稿代码,但SystemJS设置为将其用于将es6转换为javascript,没有对打字稿的明确支持,如果代码看起来不像es6,则不会使用转译器。

所以你需要明确地告诉SystemJS你的代码是es6。这是与您的示例和SystemJS 0.19一起使用的SystemJS配置。请注意,它不适用于 0.20 版本的 SystemJS,似乎除了使用插件打字稿之外别无选择。

<!DOCTYPE html>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script>
  System.config({
    map: {typescript: 'node_modules/typescript'},
    packages: {
      typescript: {main: 'lib/typescript.js', format: 'global'},
      src: {defaultExtension: 'ts', format: 'esm'}
    },
    transpiler: 'typescript',
  });
  System.import('src/main.ts');
</script>

最新更新