Parcel 如何自动注入“Web Vitals”脚本并把 LCP、FID 上报到自定义 endpoint?请给出配置片段。

解读

面试官想确认两件事:

  1. 你是否知道 Parcel 的“零配置”并不是“零插件”,遇到框架级需求时如何扩展;
  2. 你是否熟悉 Web Vitals 的采集与上报链路,并能把它做成“对业务透明”的自动化流程。
    国内大厂现网环境普遍要求:
  • 脚本必须内联或同域,避免额外 DNS/TLS 握手;
  • 上报地址往往带鉴权参数(ak / token / bid),需要运行时拼接;
  • 构建侧必须区分“开发-测试-预发-生产”多环境,避免测试脏数据。
    因此,回答要体现“插件化 + 多环境 + 性能 + 安全”四点。

知识点

  1. Parcel 2 插件体系:
    • Runtime 插件:在打包最后阶段往入口 chunk 注入运行时代码;
    • Transformer 插件:对单文件做转译,不适合做“全局注入”;
    • Optimizer 插件:做压缩,时机太晚;
      → 选 Runtime 插件最合适。
  2. web-vitals 库:
    • 提供 onLCP、onFID 等回调,数据通过 getLCP、getFID 获取;
    • 支持“reportOptions”指定“buffered: true”拿到历史值。
  3. 多环境变量:
    • Parcel 内置 NODE_ENV 与 .env.* 文件,可通过 ctx.options.env 读取;
    • 国内项目常配合“npm run build:pre”、“npm run build:prod”传参。
  4. 性能与安全:
    • 注入代码体积 < 1 kB(gzip 后 ~400 B);
    • 上报使用 navigator.sendBeacon,失败降级 fetch;
    • 只采集 3G/4G 网络下白屏后数据,避免弱网误报。

答案

  1. 安装依赖
npm i -D web-vitals
  1. 在项目根新建 parcel-config-web-vitals 插件(官方推荐本地插件放 tools/parcel-runtime-web-vitals)
// tools/parcel-runtime-web-vitals/index.mjs
import {Runtime} from '@parcel/plugin';
import {readFileSync} from 'fs';
import {fileURLToPath} from 'url';
import {join, dirname} from 'path';

const __dirname = dirname(fileURLToPath(import.meta.url));
const code = readFileSync(join(__dirname, 'inject.js'), 'utf-8');

export default new Runtime({
  async apply({bundle, options}) {
    // 只对 Web 目标且为入口 JS 做注入
    if (bundle.type !== 'js' || !bundle.isEntry) return;
    // 读取当前环境
    const env = options.env.NODE_ENV || 'development';
    const endpoint = options.env.VITALS_ENDPOINT || '/metrics/web-vitals';
    return [{
      filePath: __dirname + '/vitals-runtime.js',
      code: code
        .replace('__ENDPOINT__', JSON.stringify(endpoint))
        .replace('__ENV__', JSON.stringify(env)),
      isEntry: false,
    }];
  },
});
  1. 注入的运行时代码(inject.js)
(function(){
  if (typeof window === 'undefined') return;
  function send(metric) {
    var payload = {
      name: metric.name,
      value: metric.value,
      id: metric.id,
      url: location.href,
      env: '__ENV__'
    };
    var blob = new Blob([JSON.stringify(payload)], {type: 'application/json'});
    (navigator.sendBeacon && navigator.sendBeacon('__ENDPOINT__', blob)) ||
      fetch('__ENDPOINT__', {method: 'POST', body: blob, keepalive: true});
  }
  import('web-vitals').then(function(m){
    m.onLCP(send);
    m.onFID(send);
    // 可选:m.onCLS(send);
  });
})();
  1. 在 package.json 中注册插件并区分环境
{
  "name": "h5-app",
  "scripts": {
    "build:dev": "parcel build src/index.html",
    "build:prod": "VITALS_ENDPOINT=https://log.xxx.com/webvitals parcel build src/index.html"
  },
  "@parcel/runtime-default": false,
  "parcelRuntimeWebVitals": "tools/parcel-runtime-web-vitals/index.mjs"
}
  1. 构建验证
npm run build:prod

查看 dist/xxx.js 尾部会出现内联的采集代码,LCP/FID 会在页面加载后自动上报到 https://log.xxx.com/webvitals,且带 env="production" 字段,方便后台按环境聚合。

拓展思考

  1. 如果项目用 TypeScript,可把插件改写成 TS,用 parcel build 自身做转译,保持源码与构建同构。
  2. 对 SSR 场景(如 Next.js + Parcel 混合构建),需在 Runtime 里判断 globalThis.document 是否存在,避免在 Node 端执行。
  3. 国内移动端对“首屏时间”定义常大于 LCP,可扩展采集 FCP、TTFB,甚至把 performance.timing 回退方案也写进同一插件,实现“降级采集”。
  4. 上报失败重试:可借助 service-worker 做离线缓存,网络恢复后批量上报,提升数据完整率。
  5. 合规与隐私:采集脚本需接入公司统一埋点 SDK,通过“用户隐私开关”动态关闭,避免 GDPR/《个人信息保护法》风险。