前端模块化规范是有非常多的
在es6模块化规范之前有
Commonjs - > Nodejs
// 导入
require("xxx");
require("../xxx.js");
// 导出
exports.xxxxxx= function() {};
module.exports = xxxxx;
AMD -> requireJs
// 定义
define("module", ["dep1", "dep2"], function(d1, d2) {...});
// 加载模块
require(["module", "../app"], function(module, app) {...});
CMD -> seaJs
define(function(require, exports, module) {
var a = require('./a');
a.doSomething();
var b = require('./b');
b.doSomething();
});
UMD -> UMD是AMD和CommonJS的糅合
(function (window, factory) {
// 检测是不是 Nodejs 环境
if (typeof module === 'object' && typeof module.exports === "objects") {
module.exports = factory();
}
// 检测是不是 AMD 规范
else if (typeof define === 'function' && define.amd) {
define(factory);
}
// 使用浏览器环境
else {
window.eventUtil = factory();
}
})(this, function () {
//module ...
});
es6模块化规范出来之后上面这些模块化规范就用的比较少了
现在主要使用 import export
es6模块化规范用法
1.默认导出 和 引入
默认导出可以导出任意类型,这儿举例导出一个对象,并且默认导出只能有一个
引入的时候名字可以随便起
//导出
export default {
a:1,
}
//引入
import test from "./test";
2.分别导出
export default {
a:1,
}
export function add<T extends number>(a: T, b: T) {
return a + b
}
export let xxx = 123
//引入
import obj,{xxx,add} from './test'
3.重名问题 如果 导入的时候叫add但是已经有变量占用了可以用as重命名
import obj,{xxx as bbb,add} from './test'
console.log(bbb)
4.动态引入
import只能写在顶层,不能掺杂到逻辑里面,这时候就需要动态引入了
if(true){
import('./test').then(res => {
console.log(res)
})
}
5.解构导出
//a.ts
const fn = () => {
return "fn";
};
const fn1 = () => {
return "fn";
};
export { fn, fn1 };
//b.ts
import{ fn, fn1 } from "a.ts";
TypeSript11 tsconfig.json配置文件-CSDN博客