前端常用的模块格式有哪些?

前端中常用的模块格式主要有:CommonJS、ESM、AMD.

模块化方式特点使用场景代码示例
CommonJS
  • 同步加载模块
  • 主要用于 Node.js 环境

服务器端(Node.js)
使用 module.exportsexports 对外暴露模块

使用require导入模块

const add = require('./add');
console.log(add(1, 2));  // 输出 3
                    
ES6 Modules
  • 静态导入和导出
  • 支持树摇(Tree Shaking)
  • 浏览器和 Node.js 都支持
前端和后端(支持现代浏览器和 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
  • 通用模块定义
  • 兼容多种模块系统(CommonJS、AMD、全局变量)
跨平台库开发(同时支持浏览器和 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;
    }
  };
});
                    
posted @ 2025-03-09 22:25  我是格鲁特  阅读(11)  评论(0)    收藏  举报