Parcel 如何根据“icons/”目录下的 PNG 文件自动生成多尺寸图标并注入 manifest?请给出目录结构示例。

解读

面试官想确认三件事:

  1. 你是否知道 Parcel 2 的“零配置”并不是完全不能配置,而是靠“插件约定”搞定常见需求;
  2. 你是否熟悉 PWA 图标与 Web App Manifest 的对应关系;
  3. 你是否能把“图片→多尺寸→manifest 注入”这一条龙流程在 Parcel 里跑通,而不自己写脚本。

国内场景下,很多候选人说“Parcel 不用配置”,结果真问到图标就卡壳,只能回答“用 webpack + sharp”,直接减分。
因此,回答要体现“Parcel 有官方插件 + 约定式目录”,并给出可落地的目录结构,让面试官一听就知道你“真做过”。

知识点

  1. Parcel 2 的命名约定:
    • 以 manifest.json 或 manifest.webmanifest 结尾的文件会被 @parcel/transformer-webmanifest 接管;
    • 图片路径支持 glob 写法,且会被自动哈希、压缩、输出到 dist。
  2. @parcel/service-worker 与 @parcel/packager-raw-url 保证大文件走 URL 形式,不 base64。
  3. 图标尺寸规范:
    • 国内主流 Lighthouse 审计要求 192×192、512×512 两张即可过 PWA 门槛;
    • 若要做“自适应启动屏”,再补 180、384、1024 即可。
  4. 插件链路:
    transformer-webmanifest → 解析 icons 数组 → 触发 transformer-image 生成多尺寸 → packager-raw-url 输出文件 → runtime 自动注入 link[rel=manifest]。
  5. 缓存策略:
    Parcel 会把生成的图标哈希到 dist,并在 manifest 中写死路径,因此 HTTP 缓存头只需对静态资源配强缓存即可,符合国内 CDN 习惯。

答案

步骤一:目录结构(最简可运行示例)

project ├─ package.json ├─ src │ ├─ index.html │ ├─ manifest.webmanifest // 注意后缀 │ └─ icons │ ├─ icon-512.png // 只放最高分辨率原图即可 │ └─ icon-192.png └─ .parcelrc // 可选,国内镜像加速

步骤二:manifest.webmanifest 内容

{ "name": "示例应用", "short_name": "示例", "start_url": "/", "display": "standalone", "background_color": "#ffffff", "theme_color": "#1890ff", "icons": [ { "src": "icons/icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icons/icon-512.png", "sizes": "512x512", "type": "image/png" } ] }

步骤三:index.html 里什么都不用写,Parcel 会在构建时自动插入

<link rel="manifest" href="/manifest.7d2c4a23.webmanifest">

步骤四:构建命令

npm i -D parcel npx parcel src/index.html --public-url ./

构建产物

dist ├─ index.html ├─ manifest.7d2c4a23.webmanifest ├─ icon-192.3f1e2b4d.png └─ icon-512.a9c5d8e7.png

Parcel 会自动:

  1. 读取 manifest 中的 icons 数组;
  2. 把 icons/* 复制到 dist 并加哈希;
  3. 替换 manifest 内的 src 为最终 URL;
  4. 在 HTML 中注入 link[rel=manifest]。

若需要自动生成 96、128、384 等多尺寸,只需在 manifest 里继续写 sizes,Parcel 的 transformer-image 会调用 sharp 自动裁切,无需额外配置;国内镜像慢时可在 .parcelrc 里把 sharp 二进制源指向 https://npmmirror.com。

拓展思考

  1. 国内小程序容器内嵌 H5 时,manifest 会被忽略,如何降级?
    答:用 navigator.userAgent 判断容器,若匹配 MiniProgram 则动态写 <meta name="apple-mobile-web-app-capable"> 与 <link rel="apple-touch-icon">,走 iOS 图标规范,保证桌面快捷方式可用。
  2. 图标源文件是 SVG,如何一次输出多尺寸 PNG?
    答:把 icons/icon.svg 放进 manifest,sizes 写 “any”,Parcel 会把它当矢量图处理;若仍需固定位图,可在 .parcelrc 里配置 @parcel/transformer-svg-react 输出 React 组件,再用 @parcel/resolver-glob 批量生成位图,实现“矢量源→位图图标”流水线。
  3. 如何与 Workbox 插件结合,实现“图标缓存优先”策略?
    答:在 src/sw.js 里用 workbox.routing.registerRoute(/icon-\d+\..*\.png/, new workbox.strategies.CacheFirst()),Parcel 的 @parcel/service-worker 会把 sw.js 一并打包,无需手写 webpack 的 InjectManifest。