【问题标题】:SystemJs with TypeScript simple example fails带有 TypeScript 简单示例的 SystemJs 失败
【发布时间】:2017-10-17 12:23:15
【问题描述】:

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

index.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>

main.ts

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

alert(plusOne(1))

但是,在 Chrome 中打开 index.html 时,我看到以下错误,表明没有发生转译:

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

有什么问题?

【问题讨论】:

  • 一般来说,我认为像这样在浏览器中进行转译并不是最佳实践。我建议通常最好在构建时运行 typescript,将输出 .js 存储在浏览器从中提取的服务器上的 dist(或类似)文件夹中,而不是让浏览器进入 node_modules 以供客户端使用-side 代码,如您的示例所示。可能存在客户端转译有用的特定情况,但它可能不是默认情况。

标签: javascript typescript systemjs jspm


【解决方案1】:

发生错误是因为 SystemJS 没有使用 typescript 转译 main.ts 中的源代码,因为它没有检测到代码需要转译 - 它不包含像 exportimport 这样的 es6 特性SystemJS 检查。

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

所以你需要明确告诉 SystemJS 你的代码是 es6。这是适用于您的示例和 SystemJS 0.19 的 SystemJS 配置。请注意,它不适用于 0.20 版本的 SystemJS,看起来像 you have no other option 而不是使用 plugin-typescript

<!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>

【讨论】:

  • 没有顶级importexport 的打字稿文件不是module,因此模块加载器可能会感到困惑似乎不足为奇。添加一个虚拟的export 可能更符合模块化的精神吗?
猜你喜欢
  • 1970-01-01
  • 2019-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-09
  • 1970-01-01
  • 2016-10-08
相关资源
最近更新 更多