使用 SystemJS 在瀏覽器中輸入 Hello World
安裝 systemjs 和 plugin-typescript
npm install systemjs
npm install plugin-typescript
注意:這將安裝尚未釋出的 typescript 2.0.0 編譯器。
對於 TypeScript 1.8,你必須使用 plugin-typescript 4.0.16
建立 hello.ts
檔案
export function greeter(person: String) {
return 'Hello, ' + person;
}
建立 hello.html
檔案
<!doctype html>
<html>
<head>
<title>Hello World in TypeScript</title>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="config.js"></script>
<script>
window.addEventListener('load', function() {
System.import('./hello.ts').then(function(hello) {
document.body.innerHTML = hello.greeter('World');
});
});
</script>
</head>
<body>
</body>
</html>
建立 config.js
- SystemJS 配置檔案
System.config({
packages: {
"plugin-typescript": {
"main": "plugin.js"
},
"typescript": {
"main": "lib/typescript.js",
"meta": {
"lib/typescript.js": {
"exports": "ts"
}
}
}
},
map: {
"plugin-typescript": "node_modules/plugin-typescript/lib/",
/* NOTE: this is for npm 3 (node 6) */
/* for npm 2, typescript path will be */
/* node_modules/plugin-typescript/node_modules/typescript */
"typescript": "node_modules/typescript/"
},
transpiler: "plugin-typescript",
meta: {
"./hello.ts": {
format: "esm",
loader: "plugin-typescript"
}
},
typescriptOptions: {
typeCheck: 'strict'
}
});
注意:如果你不想進行型別檢查,請從 config.js
中刪除 loader: "plugin-typescript"
和 typescriptOptions
。另請注意,它永遠不會檢查 javascript 程式碼,特別是 html 示例中 <script>
標記中的程式碼。
測試一下
npm install live-server
./node_modules/.bin/live-server --open=hello.html
構建它用於生產
npm install systemjs-builder
建立 build.js
檔案:
var Builder = require('systemjs-builder');
var builder = new Builder();
builder.loadConfig('./config.js').then(function() {
builder.bundle('./hello.ts', './hello.js', {minify: true});
});
從 hello.ts 構建 hello.js.
node build.js
在生產中使用它
在首次使用之前,只需使用指令碼標記載入 hello.js
hello-production.html
檔案:
<!doctype html>
<html>
<head>
<title>Hello World in TypeScript</title>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="config.js"></script>
<script src="hello.js"></script>
<script>
window.addEventListener('load', function() {
System.import('./hello.ts').then(function(hello) {
document.body.innerHTML = hello.greeter('World');
});
});
</script>
</head>
<body>
</body>
</html>