如何使用 SystemJS 模块启动 Typescript 应用程序? [英] How to start a Typescript app with SystemJS modules?
问题描述
我正在使用 typescript 编译器将我的模块捆绑到一个 main.js 文件中,使用 tsconfig.json 中的这些设置:
I am using the typescript compiler to bundle my modules into one main.js file, using these settings in tsconfig.json:
"module": "system",
"out": "docs/js/main.js"
这有效,因此根据 SystemJS 文档,我只需要包含 SystemJS 生产文件并在我的 HTML 中使用这些标签启动应用程序:
This works, so according to the SystemJS documentation, I only have to include the SystemJS production file and kickstart the app with these tags in my HTML:
<script src="js/system.js"></script>
<script>
SystemJS.import('js/main.js');
</script>
我的应用:
import { Message } from "./message";
export class App {
constructor() {
let demomessage = new Message("hello");
}
}
export class Message {
constructor(str:string) {
console.log(str);
}
}
这会在 main.js 中生成此 javascript 代码:
This results in this javascript code in main.js:
System.register("message", ...) {
// message code here
});
System.register("app", ...) {
// app code here
});
我遗漏的部分(并且在 Microsoft 始终-缺少 Typescript-documentation) 是如何实际启动应用程序... SystemJS 如何知道哪个类是起点?即使我只是将 console.log 放在我的应用程序中它也不会执行....
The part that I'm missing (and that's also not explained in Microsoft's always-lacking-Typescript-documentation) is how to actually start the app... How does SystemJS know which class is the starting point? Even if I just put console.log in my app it doesn't execute....
编辑
我发现使用 system.js 而不是 system-production.js 至少可以启动这个过程.经过大量摆弄后,我让我的应用程序从以下代码开始,但它看起来很奇怪和丑陋.这是它应该如何工作???
I discovered that using system.js instead of system-production.js at least starts the process. After a lot of fiddling I got my app to start with the following code, but it looks weird and ugly. Is this how it's supposed to work???
<script src="js/system.js"></script>
<script>
// get the anonymous scope
System.import('js/main.js')
.then(function() {
// now we can get to the app and make a new instance
System.import('app').then(function(m){
let app = new m.App();
})
});
</script>
推荐答案
经过反复思考,我发现答案比预期的要简单:只需先将 bundle 作为常规 .js 文件加载,然后就可以导入直接应用:
After much head-scratching I found out the answer is more simple than expected: just load the bundle first as a regular .js file, and then you can import the app directly:
<script src="js/system.js"></script>
<script src="js/main.js"></script>
<script>
System.import('app').then(function(module) {
let a = new module.App();
});
</script>
这篇关于如何使用 SystemJS 模块启动 Typescript 应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!