如何在 Vercel 构建流程中插入自定义脚本(如代码质量检查、API 文档生成)?

解读

面试官真正想考察的是:

  1. 你是否理解 Vercel 的“零配置”边界——它只认 package.json 里的 scripts,不会替你跑额外命令;
  2. 你是否能把“质量门禁”与“产物构建”串成一条链,并保证失败即阻断部署;
  3. 你是否熟悉国内网络环境下常见卡点(husky 装不动、ESLint 规则包下载慢、私有镜像源配置等);
  4. 你是否知道预览环境(Preview)与生产环境(Production)在脚本策略上的差异,避免把耗时任务带到线上。

一句话:让自定义脚本既能在 Vercel 的 Serverless 构建容器里跑,又不破坏“git push 即上线”的体感。

知识点

  1. Build Command 覆盖机制:Vercel 优先读项目根目录 vercel.json 里的 builds.command,其次读 Framework Preset 的默认值,最后回退到 package.json scripts.build。
  2. 生命周期脚本:prebuild、build、postbuild 是 npm 原生钩子,Vercel 会按序执行;把质量检查放在 prebuild,把产物后置处理放在 postbuild,可零依赖实现“链式”。
  3. 环境变量:VERCEL_ENV、VERCEL_URL、NEXT_PUBLIC_* 等可在脚本内区分预览/生产;国内镜像加速可写进 YARN_NPM_REGISTRY_SERVER、PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD。
  4. 失败策略:任一脚本返回非 0 即整体 Build Failed,Vercel 不会继续上传静态文件,天然当“门禁”。
  5. 缓存目录:Vercel 默认缓存 node_modules/.cache、.next/cache,可在 vercel.json functions 里追加 customCacheKey,避免重复安装 Rust/Swift 工具链。
  6. 国内合规:若脚本里要调内网 SonarQube、钉钉机器人,需走公网代理或在 GitHub Action 侧预跑,再把结果以 artifact 形式带到 Vercel。

答案

分三步落地,兼顾国内网络与合规要求:

第一步:在 package.json 中声明“链式”脚本 { "scripts": { "lint": "eslint . --max-warnings 0", "type-check": "tsc --noEmit", "test:unit": "vitest run", "docs": "typedoc src/index.ts --out public/docs", "prebuild": "npm run lint && npm run type-check && npm run test:unit", "build": "next build", "postbuild": "npm run docs && node scripts/sitemap.js" } }

第二步:处理国内依赖与二进制加速 { "scripts": { "preinstall": "npx only-allow pnpm", "prepare": "husky install || true" }, "pnpm": { "registry": "https://registry.npmmirror.com", "scriptsPrependNodePath": true }, "devDependencies": { "eslint": "^8", "typedoc": "^0.25", "husky": "^8" } } 并在 vercel.json 关闭自动安装 husky(容器无 git 目录): { "buildCommand": "pnpm run build", "installCommand": "PNPM_FLAGS=--ignore-scripts pnpm install" }

第三步:按环境差异化 vercel.json { "buildCommand": "if [ "$VERCEL_ENV" = "production" ] ; then pnpm run build ; else pnpm run prebuild && pnpm run build ; fi" } 解释:预览分支仍需全量检查,生产构建跳过已跑过的 lint/test,节省 30–40 s。

至此,代码质量检查、API 文档生成全部嵌入 Vercel 原生流程,失败即阻断,成功则自动随产物部署到全球边缘节点。

拓展思考

  1. 若团队已用 GitHub Action 做重度测试,可在 Action 侧跑 lint + test,通过 Vercel GitHub 集成 的 “Ignored Build Step” 脚本判断:当检测到 git 提交信息包含 [skip vc] 或 Action 状态为失败时,直接 exit 0 阻止 Vercel 再跑一遍,节省构建分钟数。
  2. 对于需要调用内网接口生成接口文档的场景,可在 GitHub Action 里把文档产物写到 public/docs 并 git add -f,再 push 回仓库;Vercel 构建时该目录已存在,postbuild 直接复用,既解决网络隔离,又保留“文档与代码同版本”。
  3. 当项目使用 Monorepo + Turborepo 时,把 lint、test、build 拆成三个 pipeline,Vercel 构建命令改为 pnpm exec turbo run build --filter=web...,利用远程缓存把 prebuild 结果命中,平均构建时长可再降 50%。
  4. 国内 ICP 合规要求“先审后发”,可在 postbuild 脚本里把最终静态资源列表通过阿里云内容安全 API 做批量审核,审核失败则 exit 1,实现“边缘部署前的最后一道内容合规门禁”。