Typescript modules and systemjs. Instantiate class from inline script
我正在使用系统模块选项将typescript模块转换为javascript。我正在浏览器中执行此操作。
当还使用systemjs system.import加载了用于初始化由typescript生成的模块类的代码时,我可以使用此模块。
如何通过未通过System.js加载的JavaScript代码使模块中的类成为可用模块?例如。在页面中嵌入javascript?
您可以使用SystemJS导入Javascript中的模块。
假设您有一个名为app.ts的模块,该模块可导出名为value的变量。
app.ts:
1 | export let value = 'ABCASF'; |
在脚本标签中,您可以编写:
1 2 3 | System.import('app.js').then(function(appModule) { console.log(appModule.value); }, console.error.bind(console)); |
请记住,您必须赋予System.import的模块名称可能会因您的设置而异。
TypeScript类被转换为ES5函数,因此您可以以这种方式在javascript中使用它们。
example.ts:
1 2 3 4 5 6 7 8 9 | export class Example { constructor(public someValue: string, private someOtherValue: number) { } public method() { return this.someOtherValue; } } |
在脚本标签中是这样的:
1 2 3 4 5 6 7 8 9 | 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)); |