Parcel 如何集成“bundle-budget”插件,在体积超过 200 KB 时失败并输出 gzip 后大小?请给出配置。
解读
面试官想确认三件事:
- 你是否知道 Parcel 2 的插件入口是「命名空间 + 插件名」;
- 你是否理解「构建后钩子」里可以拿到 bundle 的 stat size 与 gzip size;
- 你是否能把「预算校验」做成可配置、可中断、可复现的 CI 卡点,而不是本地警告。
国内真实场景里,公司普遍用 GitLab-CI 或 GitHub Actions,面试官会追问「如果 CI 里超限如何阻断」「如何只校验业务 bundle 不校验 vendor」。因此答案里必须给出「仅对指定命名入口生效」「在 reporter 里抛异常」两个细节。
知识点
- Parcel 2 插件体系:Resolver、Transformer、Bundler、Optimizer、Reporter、Validator 六类,体积预算属于「Reporter」。
- Reporter 接口:report({ event, … }),当 event.type === 'buildSuccess' 时可遍历 bundleGraph.getBundles()。
- 获取 gzip 体积:使用内置的 @parcel/utils 中的 gzipSizeSync,避免再装第三方包。
- 中断构建:在 reporter 里直接 throw new Error('BundleBudgetError'),Parcel 会以 exitCode=1 退出,CI 即判定失败。
- 国内镜像:配置 .parcelrc 与 npm 源无关,但 CI 里建议 yarn add -D bundle-budget-reporter 前设置 registry=https://registry.npmmirror.com,避免拉包超时。
- 性能:Reporter 运行在主线程,遍历 bundle 时同步计算 gzip 即可,200 KB 阈值下耗时 < 20 ms,不会拖慢并行编译。
答案
步骤一:安装自定义 reporter(公司内网或 npm 公网均可) yarn add -D bundle-budget-reporter
步骤二:在项目根目录新建 .parcelrc { "extends": "@parcel/config-default", "reporters": [ "...", "bundle-budget-reporter" ] }
步骤三:在 package.json 中声明预算 { "parcelBudget": { "main": 204800, // 200 KB → 204800 B "gzip": true, // 以 gzip 后大小为准 "severity": "error" // 超限即抛异常,阻断 CI } }
步骤四:本地验证 yarn parcel build src/index.html --dist-dir dist 若 main.xxxxx.js.gz 体积 > 204800 B,终端输出 ✖ BundleBudgetError: main bundle gzipped 223 KB > 200 KB error Command failed with exit code 1.
GitLab-CI 示例 build: stage: build script: - yarn --registry https://registry.npmmirror.com - yarn parcel build src/index.html only: - merge_requests
当体积超限,job 失败,MR 不可合并,满足国内代码评审规范。
拓展思考
- 多入口差异化预算:在 parcelBudget 里按入口名分别写阈值,如 "vendor": 512000,"main": 204800,reporter 内部用 bundle.name 匹配。
- 警告模式:将 severity 设为 "warn",超限只打印黄字,不抛异常,适合老项目渐进优化。
- 统计上报:在 reporter 里把 gzip 体积通过企业微信机器人或飞书群机器人推送,方便 QA 与产品感知体积变化。
- 与 Lighthouse-CI 联动:Lighthouse 也测体积,但跑在 Puppeteer,耗时 30 s+;Parcel Reporter 在编译阶段即可拦截,更快。
- 微前端场景:主应用与若干子应用共用 CI,可在每个子应用根目录放独立 .parcelrc,保证子应用独立预算,避免“子应用超限却卡死主应用构建”。
- 国内合规:若项目需备案,公安要求首屏 < 500 KB,可直接把阈值写 500 KB,Reporter 抛异常后自动在 dist 目录生成 bundle-size-report.json,供审计上传。