esModule模块和commonJs模块区别

80 阅读1分钟

1.语法:

  • ES Module 使用 import 和 export(命名导出)/export default(默认导出) 关键字。
  • CommonJS 使用 require 和 module.exports/exports(导出一个对象)

2.加载方式

  • ES Module 是静态加载编译时就确定模块依赖关系。
  • CommonJS 是动态加载运行时加载模块。

3.执行顺序

  • ES Module 是异步加载,支持 async 和 await
  • CommonJS 是同步加载,模块按顺序执行。

4.作用域

  • ES Module 有自己的独立作用域不会污染全局作用域。
  • CommonJS 模块在加载时会执行,可能会污染全局作用域。

5.运行环境

  • ES Module 是浏览器环境

  • CommonJS 是node环境

// ES Module
// filepath: /path/to/file.mjs
export const name = 'GitHub Copilot';
export function greet() {
  console.log('Hello, ' + name);
}
import { name, greet } from './file.mjs';
greet();

// CommonJS
// filepath: /path/to/file.js
const name = 'GitHub Copilot';
function greet() {
  console.log('Hello, ' + name);
}
module.exports = { name, greet };
const { name, greet } = require('./file.js');
greet();