[TypeScript] Loading Compiled TypeScript Files in Browser with SystemJS

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[TypeScript] Loading Compiled TypeScript Files in Browser with SystemJS相关的知识,希望对你有一定的参考价值。

TypeScript outputs javascript, but what are you supposed to do with it? This lesson shows how to take the output and use SystemJS as the module loader so that you can use the files in your browser.

 

To use system.js, first create a index.html, add system.js file from npmcdn:
https://npmcdn.com/[email protected]/

 

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://npmcdn.com/[email protected]/dist/system.js"></script>
</head>
<body>

<script>
    System.config({
        packages: {
            "dist": {
                "defaultExtension": "js",
                "main": "main"
            }
        }
    });

    System.import("dist")
</script>
</body>
</html>

 

It tell System to load the packages. Serve "dist" folder, use default extension as js, and the main entry file is main.js. Then import dist folder.

 

Start a server:

http-server -c-1  // -c-1 -> no cache

 

Run: 

tsc -w

 

To prove it do work in broswer, add console log in the code:

//main.ts

import {Two} from ‘./two‘;

class Person{
    constructor(){
        console.log("Person!");
    }
}

new Two();
new Person();


// tow.ts
export class Two{
    constructor(){
        console.log("Two");
    }
}

 

 

以上是关于[TypeScript] Loading Compiled TypeScript Files in Browser with SystemJS的主要内容,如果未能解决你的问题,请参考以下文章

[TypeScript] Using Typings and Loading From node_modules

vue3 + typescript + axios封装(附带loading效果,...并携带跨域处理,...element-plus按需引入)

如何测试使用自定义TypeScript React Hook的组件?

按钮插件和按钮状态切换

ReactJS TypeScript 纯子组件

Webpack Code Splitting 'Loading chunk failed' 错误文件路径错误