前端常用的模块格式有哪些?
前端中常用的模块格式主要有:CommonJS、ESM、AMD.
模块化方式 | 特点 | 使用场景 | 代码示例 |
---|---|---|---|
CommonJS |
|
服务器端(Node.js) 使用require导入模块 |
const add = require('./add'); console.log(add(1, 2)); // 输出 3 |
ES6 Modules |
|
前端和后端(支持现代浏览器和 Node.js) 使用import和export |
import { add } from './math'; console.log(add(1, 2)); // 输出 3 |
AMD |
|
前端开发,现在用得少了 |
define(['math'], function(math) { console.log(math.add(1, 2)); // 输出 3 }); |
UMD |
|
跨平台库开发(同时支持浏览器和 Node.js) |
(function(root, factory) { if (typeof module === 'object' && typeof module.exports === 'object') { module.exports = factory(); } else if (typeof define === 'function' && define.amd) { define([], factory); } else { root.myModule = factory(); } })(this, function() { return { add: function(a, b) { return a + b; } }; }); |