一、CommonJS 规范
1. 主要应用场景
主要用于服务器端开发,尤其是 Node.js 环境。
2. 核心思想
使用 `require()` 函数来引入模块,使用 `module.exports` 或 `exports` 对象来导出模块中的内容。
// math.js 模块const add = (a, b) => a + b;const subtract = (a, b) => a - b;module.exports = { add, subtract };// main.js 模块const math = require("./math.js");console.log(math.add(5, 3));console.log(math.subtract(5, 3));
二、ES6 模块规范
1. 主要应用场景
在现代浏览器和支持 ES6 及以上的环境中广泛使用,适用于前端和后端开发。
2. 核心思想
使用 `import` 关键字导入模块,使用 `export` 关键字导出模块内容。
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><title>ES6 Modules Example</title></head><body><script type="module">import { add } from "./math.js";console.log(add(5, 3));</script></body></html>
// math.jsexport const add = (a, b) => a + b;
三、AMD (Asynchronous Module Definition) 规范(了解)
1. 主要应用场景
适用于浏览器端,尤其在需要异步加载模块的情况下。
2. 核心思想
使用 `define()` 函数定义模块,模块可以异步加载,适合于在浏览器中加载外部模块,防止阻塞页面加载。
<script src="require.js"></script><script>define("math", ["require", "exports", "module"], function (require,exports,module) {const add = (a, b) => a + b;const subtract = (a, b) => a - b;exports.add = add;exports.subtract = subtract;});require(["math"], function (math) {console.log(math.add(5, 3));console.log(math.subtract(5, 3));});</script>
四、CMD (Common Module Definition) 规范(了解)
1. 主要应用场景
主要用于浏览器端,与 AMD 类似,但加载方式更倾向于就近使用。
2. 核心思想
使用 `define()` 函数,与 AMD 不同的是,模块加载完成后,会将其存储在 `factory` 函数的参数中,使用时可以按需调用。
<script src="sea.js"></script><script>define(function (require, exports, module) {const add = (a, b) => a + b;const subtract = (a, b) => a - b;exports.add = add;exports.subtract = subtract;});const math = require("./math");console.log(math.add(5, 3));console.log(math.subtract(5, 3));</script>
五、UMD (Universal Module Definition) 规范(了解)
1. 主要应用场景
旨在统一 AMD 和 CommonJS 规范,使模块可以在不同环境下使用,包括浏览器和 Node.js。
2. 核心思想
使用立即执行函数,根据当前环境判断使用 AMD、CommonJS 还是作为全局变量导出。
(function (root, factory) {if (typeof define === "function" && define.amd) {// AMDdefine(["exports"], factory);} else if (typeof exports === "object") {// CommonJSfactory(exports);} else {// 全局变量root.math = factory({});}})(this, function (exports) {const add = (a, b) => a + b;const subtract = (a, b) => a - b;exports.add = add;exports.subtract = subtract;return { add, subtract };});