如何强制使用特定版本的 @babel/runtime

解读

面试官抛出这个问题,通常不是单纯问“写死版本号”这么简单。
在国内真实工程里,@babel/runtime 往往被多个上层库(antd、lodash-es、@umijs/runtime 等)间接依赖,不同子包各拉各的版本,最终 bundle 里可能同时出现 7.12.0、7.20.0 两份 runtime,导致:

  1. 包体增大 20 kB+(gzip 后仍可观);
  2. 重复辅助函数(_extends、_classCallCheck)被重复注入;
  3. 若出现 breaking change(如 7.18.0 对 regenerator-runtime 的导出方式调整),运行时直接报错。

因此“强制”= 在“依赖树层面”和“编译产物层面”同时锁死,并保证团队、CI、私有源行为一致。面试官想听的是“怎么锁、怎么验证、怎么防回退”。

知识点

  1. npm/yarn/pnpm 的依赖解析策略、hoist 规则、lockfile 机制。
  2. package.json 的 resolutions(yarn)、overrides(npm@8.3+)、pnpm.overrides 字段。
  3. Babel 插件 @babel/plugin-transform-runtime 的 version 选项与 absoluteRuntime 选项。
  4. Webpack/Rollup 的 alias/resolve.modules 优先级,以及 externals 配置。
  5. 国内私有源(verdaccio/cnpm/nexus)的 publish 权限与 sync 策略。
  6. 构建后 bundle 分析:webpack-bundle-analyzer、@bundle-analyzer/cli、source-map-explorer。
  7. 基线约束:engines、packageManager、.nvmrc、corepack。

答案

分四步落地,可直接背给面试官:

第一步:在根目录 package.json 里用“overrides”字段强制收敛版本(以 npm 为例,yarn 用 resolutions,pnpm 用 pnpm.overrides):

{
  "overrides": {
    "@babel/runtime": "7.21.0"
  }
}

这一步保证无论哪层依赖,最终 node_modules 里只有 7.21.0 一份实体。

第二步:把 @babel/plugin-transform-runtime 的 version 选项写死,与 overrides 保持同版本,防止编译时注入旧 helper:

// babel.config.js
module.exports = {
  presets: [
    ['@babel/preset-env', { modules: false }]
  ],
  plugins: [
    ['@babel/plugin-transform-runtime', {
      version: '^7.21.0',   // 关键
      absoluteRuntime: false,
      corejs: false
    }]
  ]
};

若公司把 runtime 打到私有源,可配 absoluteRuntime: '/path/to/node_modules/@babel/runtime',进一步防漂移。

第三步:在 webpack 侧加 alias 兜底,确保构建时解析到同一份:

resolve: {
  alias: {
    '@babel/runtime': require.resolve('@babel/runtime/package.json').replace(/package\.json$/, '')
  }
}

若用 Vite,在 config.resolve.alias 里同理配置。

第四步:CI 加校验脚本,一旦 lockfile 出现第二份版本即失败:

# .github/workflows/check.yml
- name: Ensure single @babel/runtime
  run: |
    npx ls-lint '@babel/runtime' --only-version 7.21.0

(ls-lint 可换成自研脚本:grep '"@babel/runtime@.*"' yarn.lock | uniq -c | wc -l 必须为 1)

四步做完,本地、CI、线上产物均只存在 7.21.0,完成“强制”。

拓展思考

  1. 如果公司同时维护多仓库(monorepo + 多项目),可把 runtime 版本写入根目录 .npmrc 的 “@babel/runtime:version=7.21.0” 配合 corepack,实现“一键全局锁”。
  2. 对于需要兼容微信小程序的场景,runtime 里默认引 regenerator-runtime 会增大 13 kB,可在 plugin-transform-runtime 里关掉 regenerator,改用 swc 或 esbuild 的 async/await downlevel,进一步瘦身。
  3. 若未来官方发布 8.0,breaking 后仍需强制 7.x,可把 overrides 写成 “<8.0.0” 并配合私有源禁止同步 8.x,实现“版本防火墙”。
  4. 面试时可以反问面试官:“咱们基线打包体积要求是多少?我可以把 runtime 的 helpers 全部 inline 并 tree-shaking,牺牲一点重复代码换零依赖,是否更符合首屏 200 kB 的指标?” 体现你对业务指标的敏感度。