ESM与CommonJS模块规范对比
1. ESM (ES Modules)
ES6引入的官方标准模块系统,使用 import 和 export 关键字。
js
// 命名导出
export const name = 'ESM';
export function sayHello() {
console.log('Hello');
}
// 默认导出
export default function main() {
// ...
}
// 导入方式
import main, { name, sayHello } from './module';2. CommonJS
Node.js 采用的模块规范,使用 require 和 module.exports。
js
// 导出方式
const name = 'CommonJS';
function sayHello() {
console.log('Hello');
}
module.exports = {
name,
sayHello
}
// 导入方式
const module = require('./module');3. 主要区别
语法差异
- ESM: 使用
import/export - CommonJS: 使用
require/module.exports
- ESM: 使用
加载时机
- ESM: 静态加载,编译时确定依赖关系
- CommonJS: 动态加载,运行时加载
导入导出方式
- ESM: 支持命名导出和默认导出
- CommonJS: 只支持单一导出对象
4. 使用示例
js
// ESM 方式
import React, { Component, PureComponent } from 'react';
// 等同于 CommonJS 方式
const React = require('react');
const { Component, PureComponent } = require('react');5. 注意事项
- ESM 是静态的,
import语句必须位于模块顶层 - CommonJS 允许动态加载,可以在条件语句中使用
require - 现代前端项目推荐使用 ESM
- Node.js 同时支持两种规范,但需要注意文件扩展名(
.mjs为 ESM,.cjs为 CommonJS)