不能全自动迁移CommonJS到ESM,因require支持动态路径而import必须静态;需“静态分析+人工校验”,跳过动态require、循环依赖等场景,jscodeshift是实用起点。

不能全自动,但能覆盖 80% 以上可确定性转换;关键在“静态分析 + 人工校验”双阶段,跳过动态 require、module.exports 赋值表达式、循环依赖等无法推断的场景。
为什么不能全靠工具自动迁移
CommonJS 的 require 是运行时调用,支持字符串拼接、变量拼路径、条件加载(如 require(env === 'dev' ? './a' : './b')),而 ESM 的 import 必须是静态字符串字面量。静态分析器无法安全推断这类表达式的实际目标模块,强行替换会导致运行时报错 Cannot find module 或导入空对象。
常见无法自动处理的情形包括:
require('./' + name + '.js')-
module.exports = {}; module.exports.fn = () => {};(非直接赋值) -
exports.default = class X {}(与 ESMexport default语义不等价) - 跨文件的
require/module.exports链式赋值(如 A.jsrequireB.js,B.js 又requireC.js 并修改其exports)
jscodeshift + 自定义 codemod 是最实用的起点
它基于 AST 操作,比正则更可靠,且社区已有成熟模板。以将 const fs = require('fs') → import fs from 'fs' 为例:
先安装:npx jscodeshift -t https://raw.githubusercontent.com/benjamn/recast/master/scripts/codemod.js ./src(基础准备)
再运行自定义迁移脚本(保存为 cjs-to-esm.js):
module.exports = function(fileInfo, api) {
const j = api.jscodeshift;
const root = j(fileInfo.source);
<p>// 替换顶层 require 调用
root.find(j.CallExpression, {
callee: { name: 'require' },
arguments: [{ type: 'StringLiteral' }]
}).replaceWith(p => {
const arg = p.node.arguments[0].value;
if (arg.startsWith('./') || arg.startsWith('../') || arg.startsWith('/')) {
return j.importDeclaration(
[j.importDefaultSpecifier(j.identifier('default'))],
j.stringLiteral(arg + '.js')
);
} else {
return j.importDeclaration(
[j.importDefaultSpecifier(j.identifier('default'))],
j.stringLiteral(arg)
);
}
});</p><p>return root.toSource();
};执行命令:npx jscodeshift -t cjs-to-esm.js ./src --extensions=js --dry --verbose=2
注意点:
- 必须加
--extensions=js,否则默认只处理.js但忽略.cjs或无扩展名配置文件 -
--dry先预览,确认无误再删掉它执行真实写入 - 该脚本不处理
require.resolve、require.cache等特殊用法,需单独 grep 排查
package.json 的 "type": "module" 不是开关,而是约束开关
加了它之后,所有 .js 文件被强制视为 ESM —— 这意味着你不能混用 require() 和 import 在同一个文件里,也不能在未改写前的旧文件中直接运行 node index.js。
实操建议:
- 先在
package.json中添加"type": "module",再批量跑 codemod,避免中途出现 “ERR_REQUIRE_ESM” 错误 - 若项目含 CLI 工具或测试入口(如
test/index.js),它们也必须同步改为 ESM 导入,否则npm test会失败 - 不推荐用
.mjs扩展名方案:它虽绕过"type"限制,但会导致 Jest、Vitest 默认不识别(需额外配transform),增加维护成本
第三方依赖的兼容性必须手动验证
即使你的代码全转成 ESM,只要依赖里有纯 CommonJS 包(如某些老版本 lodash、mysql),Node.js 仍允许 import 它们 —— 但行为不一致:
-
import pkg from 'pkg'得到的是pkg.default(如果它用了module.exports = xxx) -
import * as pkg from 'pkg'得到的是{ default: xxx },不是 CommonJS 下的{ ...xxx } - 某些包(如
sqlite3)在 ESM 下需显式import('sqlite3').then(...)动态加载,否则报ERR_UNKNOWN_FILE_EXTENSION
验证方法:
- 运行
node --experimental-loader=@esbuild-kit/esm-loader --eval "import('lodash').then(x => console.log(x))"看输出结构 - 检查
node_modules/pkg/package.json是否含"type": "module"或"exports"字段 - 对关键依赖,搜索 GitHub issues 关键词 “ESM support” 或 “v3 breaking changes”
真正麻烦的不是语法转换,而是 __dirname、__filename、require.resolve 这类 Node.js 特有 API 的重写 —— 它们没有一一对应的 ESM 原生替代,必须结合 import.meta.url + fileURLToPath 手动重构,且每个用到的地方逻辑都可能不同。


















