TypeScript入门九:TypeScript的模块

  • 关于TypeScript模块的基本使用方法

Ts的模块化语法与ES6的语法基本是一致(关于一些细节特性没有测试,请各自自行测试),然后再由tsconfig.json的module字段来描述转码类型,具体转码类型:

 "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */

Tsc就会根据module设置的模块转码类型自动转码,我们知道模块在浏览器的支持并不时很好,如果需要用到网页中还需要进一步根据模块类型降级,之前我已经有Nodejs的Commonjs规范的模块降级和ES6模块降级的相关博客:

js模块化入门与commonjs解析与应用

ES6入门十二:Module(模块化)

当然还有一些打包工具集成的相关降级工具的应用,这些已经与Ts无关,可以参考我的一些相关博客。

这里我们就来看看Ts转码Commonjs和ES6模块的一个示例代码:

1 //a.ts
2 export const PI = 3.14;
3 export namespace MyMathA{ //使用多重命名空间
4     export const strA = "This is namespace a.";
5 }
6 //inde.ts
7 import {PI,MyMathA} from './a';
8 console.log(PI);
9 console.log(MyMathA.strA);

先来看Commonjs模块模式转码后的代码:("module":"commonjs")

 1 //a.js
 2 "use strict";
 3 Object.defineProperty(exports, "__esModule", { value: true });
 4 //a.ts
 5 exports.PI = 3.14;
 6 var MyMathA;
 7 (function (MyMathA) {
 8     MyMathA.strA = "This is namespace a.";
 9 })(MyMathA = exports.MyMathA || (exports.MyMathA = {}));
10 
11 //inde.js
12 "use strict";
13 Object.defineProperty(exports, "__esModule", { value: true });
14 var a_1 = require("./a");
15 console.log(a_1.PI);
16 console.log(a_1.MyMathA.strA);

然后再来看看ES6模块模式转码后的代码:("module":"es2015")

 1 //a.js
 2 export var PI = 3.14;
 3 export var MyMathA;
 4 (function (MyMathA) {
 5     MyMathA.strA = "This is namespace a.";
 6 })(MyMathA || (MyMathA = {}));
 7 
 8 //inde.js
 9 import {PI,MyMathA} from './a';
10 console.log(PI);
11 console.log(MyMathA.strA);

猜你喜欢

转载自www.cnblogs.com/ZheOneAndOnly/p/11780561.html