无法与SystemJS一起使用Typescript。这是我的测试示例:
tsconfig.json
{
"compilerOptions": {
"module": "System",
"target": "es2015",
"outFile": "./lib/mylib.js"
},
"include": [
"./src/mylib.ts"
]
}
lib / mylib.ts
export default class MyClass {
constructor(public readonly msg: string) { }
public print() {
console.log(this.msg)
}
}
test.html
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/6.3.1/system.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/6.3.1/extras/named-register.js"></script>
<script src="lib/mylib.js"></script>
<script src="test.js"></script>
</head>
<body>
</body>
</html>
lib / mylib.js
System.register("mylib", [], function (exports_1, context_1) {
"use strict";
var MyClass;
var __moduleName = context_1 && context_1.id;
return {
setters: [],
execute: function () {
MyClass = class MyClass {
constructor(msg) {
this.msg = msg;
}
print() {
console.log(this.msg);
}
};
exports_1("default", MyClass);
}
};
});
test.js
System.import('mylib').then(() => {
let mc = new MyClass('My message')
mc.print()
})
收到错误:test.js:2 Uncaught (in promise) ReferenceError: MyClass is not defined at test.js:2
我尝试使用SystemJS,因为我需要在本地加载MyClass(没有CORS)。我将使用ES6模块,但不允许在本地导入模块。
我能发现的唯一问题是浏览器将尝试在整个全局对象上搜索MyClass
以查看是否存储了它。但是SystemJS会动态加载模块,并将它们返回到promise中,因此您将像这样包含它:
System.import('mylib').then((importedObject) => {
const MyClass = importedObject.default
let mc = new MyClass('My message')
mc.print()
})
这将简单地返回importedObject
,然后您可以指定要使用的导入。在这种情况下,您要使用默认导出,因为它存储了MyClass
。