Node.js 中使用 CommonJS 和 ESM 有什么区别?如何开启 ESM?

CommonJS(CJS):同步 require,模块是对象,运行时加载,可动态条件引入。

// CJS
const fs = require('fs')
module.exports = { a: 1 }

ESM:静态 import/export,编译期分析,支持 Tree Shaking,顶层 this 为 undefined。

// ESM
import fs from 'fs'
export const a = 1

开启方式(任选其一):

  1. package.json 写 "type": "module" → 所有 .js 视为 ESM
  2. 文件后缀用 .mjs(ESM) / .cjs(CJS)显式声明

坑:CJS 与 ESM 不能直接 require 一个 ESM 模块(需动态 import());ESM 里没有 __dirname,可用 import.meta.url + fileURLToPath 代替。

同分类其他题目