JS 模块
JS 中常用的模块:
ES module
浏览器原生支持的模块,typescript也是参考的这个模块
编写模块文件 "test.js"
export const name = 'square';
导入模块并测试
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <input id="input"> <script type="module"> import {name} from './test.js'; alert(name); </script> </body> </html>
导出多个元素
export { name, draw, reportArea, reportPerimeter };
默认导出
export default randomSquare;
导入的时候,默认到处只允许导出一个模块,所以导入的时候,任何命名都可以找到这个模块
import randomxxx from './modules/square.mjs';
除了ES模块,常见的模块还有Common JS模块
// 导入模块 const constants_1 = require("./constants"); // 导出 exports.twoPi = constants_1.valueOfPi * 2;
AMD模块
// 导入模块 define(["require", "exports", "./constants"], function (require, exports, constants_1) { // 导出 exports.twoPi = void 0; exports.twoPi = constants_1.valueOfPi * 2; });
UMD模块
(function (factory) { if (typeof module === "object" && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports", "./constants"], factory); } })(function (require, exports) { exports.twoPi = void 0; });
SystemJS模块
System.register(["./constants"], function (exports_1, context_1) { var constants_1, twoPi; var __moduleName = context_1 && context_1.id; return { setters: [ function (constants_1_1) { constants_1 = constants_1_1; } ], execute: function () { exports_1("twoPi", twoPi = constants_1.valueOfPi * 2); } }; });
Google还定义了goog模块
// 当前文件就是一个模块,并且命名为'foo' goog.module('foo'); // 导入模块 const Quux = goog.require('baz.Quux'); // 导出 exports.Bar = function() { /* … */ };
CommonJS和AMD导出的时候,都是给exports上面记东西,只是导入不太一样。
CommonJS导入直接调用require,AMD导入需要调用define方法。
编写Typpescript的时候,采用ES模块,但是编译的时候,可以通过不同选项,产出不同类型的模块代码
{ "compilerOptions": { "module": "commonjs" } }
有这些选项:
-
none
-
commonjs
-
amd
-
umd
-
system
-
es6
/es2015
-
es2020
-
es2022
-
esnext
-
node16
-
nodenext
举例如下:
export class Student { public sayName(): void { console.log("aaa"); } }
使用如下的tsconfig
{ "compilerOptions": { "target": "ES5", "module": "ES2015", "importHelpers": true, "lib": ["es2015", "DOM"] }, "include": [ "test.ts" ] }
编译后的js文件,由于使用ES模块,可以直接在浏览器运行了:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <input id="input"> <script type="module"> import { Student } from './test.js'; var stu = new Student(); stu.sayName(); </script> </body> </html>