.ts文件不被视为TypeScript模块

Est*_*ask 7 typescript systemjs

这是SystemJS + TypeScript插件,由官方Angular plunk模板创建.

它抛出

(SystemJS)SyntaxError:const声明中缺少初始值设定项

在eval()

...

当文件不包含importexport语句时,错误并明显将.ts文件评估为普通JavaScript :

main.ts

const foo: boolean = 'foo';

console.log(foo);
Run Code Online (Sandbox Code Playgroud)

config.js

System.config({
  //use typescript for compilation
  transpiler: 'typescript',
  //typescript compiler options
  typescriptOptions: {
    emitDecoratorMetadata: true
  },
  paths: {
    'npm:': 'https://unpkg.com/'
  },
  //map tells the System loader where to look for things
  map: {

    'app': './src',
    ...
  },
  //packages defines our app package
  packages: {
    app: {
      main: './main.ts',
      defaultExtension: 'ts'
    },
    ...
  }
});
Run Code Online (Sandbox Code Playgroud)

的index.html

...
<script src="https://unpkg.com/systemjs@0.19.31/dist/system.js"></script>
<script src="config.js"></script>
<script>
System.import('app')
  .catch(console.error.bind(console));
</script>
...
Run Code Online (Sandbox Code Playgroud)

但是当文件有ES6模块的迹象时,同样的插件很好:

main.ts

const foo: boolean = 'foo';

console.log(foo);

export default null;
Run Code Online (Sandbox Code Playgroud)

显然,如果文件具有.ts扩展名,我宁愿将其评估为TypeScript,无论它是否导入.

为什么会在此设置中发生这种情况?怎么解决这个问题?

tha*_*you 4

SystemJS 可能会按如下方式工作:

> System.import('app')
  - where is 'app'?
> map: { 'app': './src', ...
  - Okay, 'app' is './src'
  - './src' ??
> packages: { app: { main: './main.ts',
  - Aha, './src/main.ts'
> ./src/main.ts
  - Which format??
  - 'system' ? -> No
  - 'esm' ? -> No (if YES, use transpiler: 'typescript')
  - 'amd' ? -> No
  - 'cjs' ? -> No
  - 'global' ? -> Yes -> No transpiler needed.
> evaluate ./src/main.ts
  - What is ':string' in JavaScript?
  - Exception!!!
Run Code Online (Sandbox Code Playgroud)

模块格式检测

当未设置模块格式时,将使用基于正则表达式的自动检测。这种模块格式检测永远不会完全准确,但可以很好地满足大多数用例。

如果自动检测失败,则必须手动指定。

方法一:在源码中添加提示

ex1:添加export(来自问题)

const foo: boolean = 'foo';
console.log(foo);
export default null;
Run Code Online (Sandbox Code Playgroud)

例2:添加export

export const foo: boolean = 'foo';
console.log(foo);
Run Code Online (Sandbox Code Playgroud)

方法二:添加format配置

ex1: 包/路径/元/模式(./main.ts 或 ./*.ts)/format

packages: {
    app: {
      main: './main.ts',
      defaultExtension: 'ts',
      meta: {
       './main.ts': {
           format: 'esm'
        }
      } 
    }
Run Code Online (Sandbox Code Playgroud)

ex2: 包/路径/format

packages: {
    app: {
      main: './main.ts',
      defaultExtension: 'ts',
      format: 'esm'
    }
}
Run Code Online (Sandbox Code Playgroud)

ex3:元/模式(需要app/前缀)/ format(外部包)

meta: {
    'app/main.ts': {
        format: 'esm'
    }
}
Run Code Online (Sandbox Code Playgroud)