当您没有在命令行上为 tsc 指定编译器选项并且您没有 tsconfig.json 文件时,typescript 使用默认值。根据typescript documentation 的默认值是es3 用于发出的语言,commonjs 用于模块加载器。我认为这些选项不可接受,因此我在 tsconfig.json 文件中指定了不同的选项。尝试按如下方式设置项目,我认为您会对结果感到满意。看起来工作量很大,但您可以在完成后将项目导出到模板中,并且您无需再做一次。这假设您在您的机器上设置了npm。
在 VS 2017 中新建一个项目,选择 ASP.NET Web Application(.NET Framework) 作为模板。我知道这听起来可能不对,但请耐心等待,因为您最终会得到一个最小的项目,其中不包含您不想要的太多内容。在向导的下一页上,选择 Empty 并取消选中每个框并使其不进行身份验证。完成向导。
在项目的根级别添加以下文件。
package.json:
{
"version": "1.0.0",
"name": "asp.net",
"author": "you",
"private": true,
"dependencies": {
"core-js": "^2.5.3",
"systemjs": "^0.21.0"
}
}
tsconfig.json:
{
"compilerOptions": {
"module": "system",
"target": "es5",
"noImplicitAny": true,
"noEmitOnError": true,
"sourceMap": true
},
"files": [
"app/app.ts"
],
"exclude": [
"node_modules"
]
}
system.config.js:
(function (global) {
SystemJS.config({
paths: {
'npm:': '/node_modules/'
},
map: {
app: '/app'
},
packages: {
app: {
main: 'app.js',
defaultExtension: 'js'
}
}
})
})(this);
index.html:
<!DOCTYPE html>
<html>
<head>
<base href="/" />
<meta charset="utf-8" />
<title>Typescript with SystemJS and Modules Demo</title>
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/systemjs/dist/system.js"></script>
<script src="system.config.js"></script>
<script>
SystemJS.import("app/app.js").catch(function (e) { console.log(e); });
</script>
</head>
<body>
<div id="personDiv"></div>
</body>
</html>
另外,创建一个app 文件夹并将以下2个文件放入其中:
app.ts:
import { Person } from "./person";
export class App {
constructor() {
let person: Person = new Person();
let div: HTMLDivElement = <HTMLDivElement>document.getElementById('personDiv');
div.innerHTML = person.getName();
}
}
// Use this assignment to start execution.
let a: App = new App();
// The following doesn't appear to work with SystemJS. It does with plain TypeScript.
// It is probably because SystemJS already defines a listener for window.onload,
// although I haven't verified that.
//window.onload = () => {
// let a: App = new App();
// let person = new Person();
// alert(person.getName);
//}
person.ts:
export class Person {
fullName: string;
constructor() {
this.fullName = "Test Guy";
}
getName():string {
return this.fullName;
}
}
然后构建并运行应用程序。结果应显示导入工作正常。