【发布时间】:2017-08-24 07:17:12
【问题描述】:
我最近一直在研究和使用 TypeScript 做简单的“hello worlds”。有些事情我觉得我无法理解,那就是如何将 System.js 与 TypeScript 一起使用。互联网上的每一个教程或演示都是关于 Angular2 的,我还不想参与 Angular 2。
例如,我的项目结构如下:
RootFolder
|
| _lib
| ...... ts (where .ts files are)
|
| components (where compiled .js files are)
| libraries
| ......... systemjs (where system.js is)
|
| index.html
| tsconfig.json
我的 tsconfig.json 文件看起来像:
{
"compileOnSave": true,
"compilerOptions": {
"noImplicitAny": true,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5",
"module": "system",
"moduleResolution": "node",
"outDir": "./components"
},
"exclude": [
"node_modules",
"wwwroot"
],
"include": [
"./_lib/ts/**/*"
]
}
TypeScript 编译按预期工作,没有任何问题。我创建了一个名为“Alerter”的简单类,其中包含以下代码:
//alerter.ts
class Alerter {
showMessage(): void {
alert("Message displayed.");
}
}
export default Alerter
还有一个 app.ts(这是我的“主”应用程序文件),代码如下:
//app.ts
import Alerter from "./alerter";
console.log("app.js included & executed");
function test() {
console.log("test called");
const alt = new Alerter();
alt.showMessage();
};
在我的 index.html 中,我只想用 System.js 导入这个 app.js,并且只想从控制台调用“test”函数。但它不起作用。无论我做什么,我都无法访问该功能。我看到第一行 console.log 正在执行,但是当我尝试从 chrome 控制台调用 test() 时,它是未定义的。
如果我从 main.ts 中删除“alerter”类依赖项,一切正常。因为编译后的 app.js 只包含 console.log 调用和函数定义。
这是我在 index.html 中的 System.js 调用
System.config({
packages: {
"components": {
defaultExtension: "js"
}
}
});
System.import("components/app");
我现在真的很绝望,我想我应该回到 Jquery 时代。这很简单,但不能让它工作。
【问题讨论】:
-
我为演示做了一个简单的 TS + SystemJS 项目设置,也许它会对你有所帮助。 github.com/Toskv/talk.timjs.typescript/tree/master/modules/live
-
@toskv 谢谢你到目前为止真的很有帮助。我仍在检查,但已经给了我很好的洞察力。
-
如果你想从 index.html 访问函数,你必须加载导出它,这样你就可以在模块加载完成后使用它。 System.import 返回一个承诺,响应将包含您要求的模块。 :)
-
这可能有助于理解我最后的评论。 stackoverflow.com/questions/36313093/…
标签: typescript module systemjs typescript2.0 es6-modules