如何仅通过 CLI 参数强制关闭缓存并清理历史缓存?请给出跨平台命令。

解读

面试官想知道两件事:

  1. 你是否了解 Parcel 默认会启用磁盘缓存(.parcel-cache)以加速二次构建;
  2. 你是否能在不手动删除目录的前提下,用官方提供的 CLI 参数一次性“关闭缓存 + 清空旧缓存”,并且命令在 Windows / macOS / Linux 下都能直接复制粘贴运行。
    国内项目多在 CI 或云主机里跑脚本,如果候选人只会 rm -rf,会被追问“CI 里怎么跨平台?”、“如果缓存目录被配置到了自定义路径怎么办?”。因此必须给出 Parcel 原生参数,而不是操作系统指令。

知识点

  1. Parcel 2.x 把缓存目录固定为项目根目录下的 .parcel-cache,可通过 --cache-dir <path> 自定义。
  2. --no-cache 仅禁用当前构建的缓存读写,不会删除已有缓存。
  3. --no-cache --cache-dir .parcel-cache 配合 rm -rf 属于“半官方”做法,但跨平台需要 rimraf 或 del-cli,增加依赖。
  4. Parcel 2.8.0 起内置 --clear-cache(别名 --clearCache),行为是:
    • 启动前同步删除缓存目录;
    • 自动识别 --cache-dir 的值;
    • 与 --no-cache 互斥但可连用,先清再禁;
    • 在 Windows cmd、PowerShell、bash、zsh 下表现一致。
  5. 国内常见误区:
    • 把 .parcel-cache 写进 .gitignore 就完事,但 CI 镜像层复用仍会读到旧缓存;
    • 用 parcel build --no-cache 以为缓存就没了,其实目录还在,下次 dev 又读回来。

答案

跨平台一次性命令(Parcel ≥2.8.0):

# 开发模式
npx parcel src/index.html --no-cache --clear-cache

# 生产构建
npx parcel build src/index.html --no-cache --clear-cache

解释:

  • --clear-cache 让 Parcel 在启动构建前同步删除缓存目录,无需手动 rm;
  • --no-cache 确保本次构建不再写入新缓存;
  • 使用 npx 保证无论全局是否安装 parcel 都能运行,且 Windows / macOS / Linux 通用。

若 CI 里缓存路径被自定义为 .tmp/parcel-cache,则:

npx parcel build src/index.html --cache-dir .tmp/parcel-cache --no-cache --clear-cache

拓展思考

  1. 旧版本(<2.8.0)没有 --clear-cache,可降级方案:

    // package.json 脚本
    "scripts": {
      "clean:parcel": "rimraf .parcel-cache",
      "build:ci": "npm run clean:parcel && parcel build --no-cache"
    }
    

    需要额外安装 rimraf 保证跨平台。

  2. 在 GitHub Actions / GitLab CI 中,可把 .parcel-cache 加入缓存 key,但每日首次流水线强制失效:

    - run: npx parcel build --no-cache --clear-cache
      if: ${{ github.run_number == 1 }}
    

    兼顾速度与一致性。

  3. 若团队使用 Yarn PnP,缓存目录可能位于 .yarn/.parcel-cache,同样通过 --cache-dir 指定即可,--clear-cache 会跟随路径删除,无需改动脚本。