Typescript 模块和 systemjs。从内联脚本实例化 class

Typescript modules and systemjs. Instantiate class from inline script

我正在使用系统模块选项将打字稿模块转译为 javascript。我正在浏览器中执行此操作。

当初始化由 typescript 生成的模块 class 的代码也使用 systemjs system.import.

加载时,我能够使用这个模块

如何使 class 成为模块的一部分,可从未通过 systemjs 加载的 javascript 代码中获取?例如。在页面中嵌入 javascript?

您可以使用 SystemJS 导入 Javascript 中的模块。

假设您有一个名为 app.ts 的模块,它导出一个名为 value.

的变量

app.ts:

export let value = 'ABCASF';

在脚本标签中你可以这样写:

System.import('app.js').then(function(appModule) {
  console.log(appModule.value);
}, console.error.bind(console));

请记住,您必须为 System.import 提供的模块名称可能会因您的设置而异。

TypeScript 类 被转译为 ES5 函数,因此您可以通过这种方式在 javascript 中使用它们。

example.ts:

export class Example {
  constructor(public someValue: string, private someOtherValue: number) {

  }

  public method() {
    return this.someOtherValue;
  }
}

并在脚本标签中这样写:

  System.import('example.js').then(function(example) {
    // Example class is a function on the module 
    // use new to make a new instance
    var value = new example.Example('a', 5);

    // work as usual 
    console.log(value.method());

  }, console.error.bind(console));