使用TypeScript简单示例的SystemJs失败

时间:2017-05-17 21:24:44

标签: javascript typescript systemjs jspm

我正在尝试将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
    ...

有什么问题?

1 个答案:

答案 0 :(得分:1)

发生错误是因为SystemJS不使用typescript来转换main.ts中的源代码,因为它没有检测到代码需要被转换 - 它不包含export等es6功能或SystemJS检查的import

这就是transpiler选项的工作方式。你想设置transpiler: '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>
相关问题