使用 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>