如何使用 gulp-babel 将 ESM 转 CJS 并保持动态 import 为异步?
解读
面试官真正想考察的是:
- 你是否理解 gulp-babel 只是 Babel 的“搬运工”,核心配置在 babel.config.js 或 .babelrc.js;
- 你是否知道 @babel/plugin-transform-modules-commonjs 会把所有 import 翻译成 require,从而把“动态 import()”退化成“同步 require”——这是国内很多候选人直接掉坑的点;
- 你是否掌握 babel 的 overwrites 或插件时序 技术,让动态 import 保持为异步调用,而不是被插件误杀;
- 你是否能把这条链路串进 Gulp 的流式管道 里,并给出可落地的中国国内工程化方案(兼容 webpack 微前端、qiankun、vite 旧库迁移等场景)。
知识点
- gulp-babel 的本质:把 Vinyl 文件内容交给 Babel Core,再把编译结果塞回流;
- @babel/plugin-transform-modules-commonjs 的默认行为:所有 import 语句 → require,import() → require;
- @babel/plugin-syntax-dynamic-import:只做语法解析,不做转换,必须显式保留;
- overrides 配置:让 Babel 只对匹配文件走指定插件集合,避免“一刀切”;
- Gulp 管道顺序:gulp.src → babel → gulp.dest,中间若需 sourcemap 需加 gulp-sourcemaps;
- 国内常见陷阱:
– 把 babel 配置写到 .babelrc,导致 monorepo 子包继承错误;
– 忘记把 @babel/runtime 与 @babel/plugin-transform-runtime 一起用,造成重复 helpers;
– 动态 import 里使用模板字符串,被误识别为“不可静态分析”,需要 @babel/plugin-proposal-dynamic-import 保持异步。
答案
-
安装依赖(国内镜像源示例,淘宝源已转 npmmirror):
npm i -D gulp gulp-babel @babel/core @babel/preset-env \ @babel/plugin-transform-modules-commonjs \ @babel/plugin-syntax-dynamic-import \ @babel/plugin-proposal-dynamic-import \ @babel/plugin-transform-runtime \ @babel/runtime -
在项目根新建 babel.config.js,用 overrides 让“动态 import”不被 commonjs 插件降级:
module.exports = { presets: [ ['@babel/preset-env', { modules: false }] // 先不关模块,交给插件细粒度控制 ], plugins: [ '@babel/plugin-syntax-dynamic-import', '@babel/plugin-proposal-dynamic-import', ['@babel/plugin-transform-modules-commonjs', { // 关键:禁止把 import() 转成 require importInterop: 'node', allowTopLevelThis: true, loose: true }], ['@babel/plugin-transform-runtime', { corejs: 3 }] ], // 对真正需要 ESM 转 CJS 的业务代码生效 overrides: [{ test: ['./src/**/*.js'], plugins: [ ['@babel/plugin-transform-modules-commonjs', { // 再次声明,防止被别的 preset 覆盖 noInterop: false, importInterop: 'node' }] ] }] }; -
编写 gulpfile.js(CommonJS 写法,兼容国内老项目):
const { src, dest, series } = require('gulp'); const babel = require('gulp-babel'); const sourcemaps = require('gulp-sourcemaps'); function esm2cjs() { return src('src/**/*.js') .pipe(sourcemaps.init()) .pipe(babel()) // 使用上面 babel.config.js .pipe(sourcemaps.write('.')) .pipe(dest('lib')); } exports.build = series(esm2cjs); -
验证:
编译前源码export const foo = 1; export async function bar() { const mod = await import('./lazy.js'); return mod.default; }编译后产物
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.foo = void 0; const foo = exports.foo = 1; async function bar() { const mod = await import('./lazy.js'); // 依旧是异步 import,未被 require 替代 return mod.default; } exports.bar = bar;至此,ESM 语法已转 CJS,但动态 import() 保持异步,符合 Node.js 14+ 的 ES Module 兼容规范,也满足国内微前端子应用懒加载需求。
拓展思考
- 如果项目同时存在 type: "module" 的 ESM 包与遗留 CJS 包,可用 Gulp 条件分支 + gulp-if 把两种产物分别输出到 es/ 与 lib/,并在 package.json 中配置
"exports": { ".": { "import": "./es/index.js", "require": "./lib/index.js" } },实现双模式发包,这是国内大型组件库(如 Ant Design 5.x 子包)的通用做法。 - 动态 import 里若使用 webpackChunkName 魔法注释,需再引入 @babel/plugin-syntax-import-meta 与 babel-plugin-dynamic-import-node-babel-7,否则在 Jest / Node 单测环境会报错;
- 当产物要跑在 Electron 主进程 时,需把 target 设成 'node',并关闭 preset-env 的 modules 转换,再用 @vercel/ncc 做一次性打包,避免原生模块加载失败;
- 国内 CI 环境(阿里 Yunxiao、腾讯 CODING)常把 node_modules 缓存到远端,记得把 babel.config.js 加入缓存指纹,否则会出现“改配置不生效”的假象;
- 最后,gulp-babel 本身不会缓存,大项目请配套 gulp-cache 或 gulp-babel 的 { cacheDirectory: true } 选项,可把二次编译速度提升 60% 以上,面试时把这条“性能优化”主动抛出,通常能加不少分。