·更新于 2026年4月21日· 59 次浏览 JavaScript工程化
ES Modules 与 CommonJS:互操作与打包边界
`import` / `export` 静态分析与 tree-shaking;`require` 动态路径限制;在 Node 与 Vite 中混用时的典型坑。
作者
ZHOU YI
ESM 在编译期即可确定依赖图,有利于摇树优化;CJS 的 module.exports 多在运行时解析,工具链难以静态剔除。
js
// CJS 中动态 import 返回 Promise
async function load() {
const { fn } = await import('./plugin.mjs')
return fn()
}Node 字段
"type": "module"与.cjs/.mjs扩展名__dirname在 ESM 中需import.meta.url自行推导- 部分仅 CJS 包需
createRequire或等待官方 dual package