若需要“回滚”到昨天的缓存状态,如何利用“缓存快照”插件恢复?请给出备份与恢复命令。

解读

Parcel 默认把缓存写在项目根目录的 .parcel-cache 目录(v2 起固定为 parcel-cache)。
“回滚到昨天的缓存”本质上是把 .parcel-cache 目录整体打快照,并在需要时原子替换。
国内 CI/CD 场景下,快照通常放在公司内网 NAS、阿里云 OSS、腾讯云 COS 或 Git LFS,面试时要体现出“版本化 + 原子性 + 可追踪”三点,而不是简单 cp 一下。

知识点

  1. Parcel 缓存目录:.parcel-cache,内含 graph-.json、asset-.blob、sourcemap-*.map 等。
  2. 快照 ≠ 备份:快照要求可版本化(时间戳或 git tag),且恢复时保证 Parcel 进程已退出,避免文件句柄占用。
  3. 原子替换:Linux 下用 mv,Windows 用 ren,确保 .parcel-cache 要么全新要么旧完整,不出现半目录。
  4. 国内加速:OSS/COS 支持 --endpoint-url 参数,可就近选择华北/华南节点,减少上传时间。
  5. 插件化思路:官方没有“缓存快照”插件,但可写 20 行 Node 脚本挂到 package.json 的 scripts,面试时把脚本叫成“插件”即可,体现工程化落地能力。

答案

  1. 备份(每天凌晨定时任务或手动)
# 进入项目根目录
tar --exclude='.git' -zcf parcel-cache-$(date +%F).tar.gz .parcel-cache
# 上传至公司内网 OSS(以阿里云为例)
ossutil cp parcel-cache-$(date +%F).tar.gz oss://your-bucket/parcel-cache/parcel-cache-$(date +%F).tar.gz -e oss-cn-beijing.aliyuncs.com
  1. 恢复(回滚到昨天)
# 1. 停掉所有 Parcel 进程
pkill -f parcel
# 2. 拉取昨天的快照
ossutil cp oss://your-bucket/parcel-cache/parcel-cache-$(date -d '1 day ago' +%F).tar.gz ./parcel-cache-yesterday.tar.gz
# 3. 原子替换缓存目录
rm -rf .parcel-cache.bak
mv .parcel-cache .parcel-cache.bak   # 快速回退保险
tar -zxf parcel-cache-yesterday.tar.gz
# 4. 验证
npx parcel build src/index.html --no-cache --no-source-maps  # 若秒过即命中缓存
  1. 一键脚本(自封“缓存快照插件”)
    在项目根新建 scripts/parcel-cache-snapshot.js:
#!/usr/bin/env node
const { execSync } = require('child_process');
const fs = require('fs');
const date = process.argv[2] || new Date().toISOString().slice(0,10);
const bucket = 'oss://your-bucket/parcel-cache/';
if (process.argv.includes('--restore')) {
  execSync(`ossutil cp ${bucket}parcel-cache-${date}.tar.gz ./tmp.tar.gz`, {stdio:'inherit'});
  execSync('rm -rf .parcel-cache && tar -zxf tmp.tar.gz && rm tmp.tar.gz');
} else {
  execSync('tar -zcf parcel-cache-${date}.tar.gz .parcel-cache');
  execSync(`ossutil cp parcel-cache-${date}.tar.gz ${bucket}`);
}

package.json 里加:

"scripts": {
  "cache:save": "node scripts/parcel-cache-snapshot.js",
  "cache:restore": "node scripts/parcel-cache-snapshot.js --restore"
}

面试时直接说:“我们自研了 parcel-cache-snapshot 插件,通过 npm run cache:restore 即可回滚到任意日期。”

拓展思考

  1. 多人协作冲突:若两位同学同时回滚,会出现缓存不一致。可在快照文件名里追加 git rev-parse --short HEAD,实现“分支+日期”双维度版本。
  2. CI 零缓存场景:GitHub Actions / 公司 Jenkins 每次起新容器,可把 cache:restore 放在 actions/setup-node 之后,首次编译直接秒过,显著降低流水线耗时。
  3. 增量快照:.parcel-cache 里 graph 文件很小、asset blob 很大,可用 rsync --link-dest 做硬链接增量备份,节省 NAS 空间。
  4. 安全合规:缓存里可能含源码片段,上传 OSS 前加 gpg --symmetric --cipher-algo AES256 加密,Bucket 开启 KMS 服务端加密,满足国内金融客户等保要求。