模块化历史(Module History)
JavaScript 模块化的发展历程和不同规范。
📚 模块化发展历程
1. 无模块化时代(1995-2009)
早期 JavaScript 没有模块系统,通过全局变量共享代码:
// math.js
var add = function(a, b) {
return a + b;
};
// app.js
console.log(add(1, 2)); // 依赖全局变量问题:
- 全局变量污染
- 命名冲突
- 依赖关系不明确
- 难以维护
2. CommonJS(2009)
Node.js 采用的模块系统,使用 require 和 module.exports。
语法
// math.js
function add(a, b) {
return a + b;
}
module.exports = { add };
// 或者
exports.add = add;
// app.js
const { add } = require('./math.js');
console.log(add(1, 2));特点
- ✅ 同步加载
- ✅ 适合服务端
- ❌ 不适合浏览器(同步阻塞)
3. AMD(Asynchronous Module Definition,2009)
RequireJS 采用的异步模块定义规范。
语法
// math.js
define(['dependencies'], function(deps) {
function add(a, b) {
return a + b;
}
return { add };
});
// app.js
require(['math'], function(math) {
console.log(math.add(1, 2));
});特点
- ✅ 异步加载
- ✅ 适合浏览器
- ❌ 语法复杂
- ❌ 需要加载器(RequireJS)
4. UMD(Universal Module Definition,2011)
通用模块定义,兼容 CommonJS、AMD 和全局变量。
语法
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['exports'], factory);
} else if (typeof exports === 'object') {
// CommonJS
factory(exports);
} else {
// 全局变量
factory(root);
}
}(typeof self !== 'undefined' ? self : this, function (exports) {
function add(a, b) {
return a + b;
}
exports.add = add;
}));特点
- ✅ 兼容多种环境
- ❌ 代码冗长
- ❌ 主要用于库开发
5. ES6 模块(2015)
JavaScript 官方模块系统,使用 import 和 export。
语法
// math.js
export function add(a, b) {
return a + b;
}
// app.js
import { add } from './math.js';
console.log(add(1, 2));特点
- ✅ 官方标准
- ✅ 静态分析
- ✅ Tree shaking
- ✅ 严格模式
- ⚠️ 需要现代浏览器或转译
🔄 规范对比
| 规范 | 加载方式 | 适用环境 | 语法复杂度 |
|---|---|---|---|
| CommonJS | 同步 | Node.js | 简单 |
| AMD | 异步 | 浏览器 | 中等 |
| UMD | 同步/异步 | 通用 | 复杂 |
| ES6 模块 | 静态/动态 | 通用 | 简单 |
💡 使用建议
Node.js 环境
// ✅ 推荐:使用 ES6 模块(Node.js 14+)
// package.json
{
"type": "module"
}
// math.js
export function add(a, b) {
return a + b;
}
// app.js
import { add } from './math.js';浏览器环境
// ✅ 推荐:使用 ES6 模块 + 构建工具
// 使用 Vite、Webpack 等工具转译和打包
import { add } from './math.js';库开发
// ✅ 推荐:同时支持 CommonJS 和 ES6 模块
// package.json
{
"main": "dist/index.cjs.js", // CommonJS
"module": "dist/index.esm.js", // ES6 模块
"exports": {
".": {
"import": "./dist/index.esm.js",
"require": "./dist/index.cjs.js"
}
}
}🔗 相关链接
参考: