如何配置持续集成 (CI) 构建缓存
为了提升构建性能,Next.js 会将缓存保存到 .next/cache
目录,这些缓存在不同构建之间共享。
要在持续集成 (CI) 环境中利用此缓存,您需要配置 CI 工作流,确保构建之间能正确保留缓存。
如果您的 CI 未配置为在构建间保留
.next/cache
,可能会遇到 未检测到缓存 错误。
以下是常见 CI 提供商的缓存配置示例:
Vercel
Next.js 缓存已自动为您配置,无需任何额外操作。如果您在 Vercel 上使用 Turborepo,请参阅此处了解更多。
CircleCI
在 .circleci/config.yml
中编辑 save_cache
步骤,包含 .next/cache
:
steps:
- save_cache:
key: dependency-cache-{{ checksum "yarn.lock" }}
paths:
- ./node_modules
- ./.next/cache
如果没有 save_cache
配置,请遵循 CircleCI 的 构建缓存设置文档。
Travis CI
在 .travis.yml
中添加或合并以下内容:
cache:
directories:
- $HOME/.cache/yarn
- node_modules
- .next/cache
GitLab CI
在 .gitlab-ci.yml
中添加或合并以下内容:
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/
- .next/cache/
Netlify CI
使用 Netlify 插件 配合 @netlify/plugin-nextjs
。
AWS CodeBuild
在 buildspec.yml
中添加(或合并)以下内容:
cache:
paths:
- 'node_modules/**/*' # 缓存 `node_modules` 以加速 `yarn` 或 `npm i`
- '.next/cache/**/*' # 缓存 Next.js 以加速应用重建
GitHub Actions
使用 GitHub 的 actions/cache,在工作流文件中添加以下步骤:
uses: actions/cache@v4
with:
# 关于 `yarn`、`bun` 或其他包管理器的缓存配置,请参阅 https://github.com/actions/cache/blob/main/examples.md,或使用 actions/setup-node 的缓存功能 https://github.com/actions/setup-node
path: |
~/.npm
${{ github.workspace }}/.next/cache
# 当包或源文件变更时生成新缓存
key: ${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json') }}-${{ hashFiles('**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx') }}
# 如果源文件变更但包未变,则从现有缓存重建
restore-keys: |
${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json') }}-
Bitbucket Pipelines
在 bitbucket-pipelines.yml
的顶层(与 pipelines
同级)添加或合并以下内容:
definitions:
caches:
nextcache: .next/cache
然后在流水线的 step
的 caches
部分引用它:
- step:
name: your_step_name
caches:
- node
- nextcache
Heroku
使用 Heroku 的 自定义缓存,在顶层 package.json 中添加 cacheDirectories
数组:
"cacheDirectories": [".next/cache"]
Azure Pipelines
使用 Azure Pipelines 的 缓存任务,在流水线 yaml 文件中执行 next build
的任务前添加以下任务:
- task: Cache@2
displayName: '缓存 .next/cache'
inputs:
key: next | $(Agent.OS) | yarn.lock
path: '$(System.DefaultWorkingDirectory)/.next/cache'
Jenkins (Pipeline)
使用 Jenkins 的 Job Cacher 插件,在 Jenkinsfile
中通常运行 next build
或 npm install
的位置添加以下构建步骤:
stage("Restore npm packages") {
steps {
// 基于 GIT_COMMIT 哈希将锁文件写入缓存
writeFile file: "next-lock.cache", text: "$GIT_COMMIT"
cache(caches: [
arbitraryFileCache(
path: "node_modules",
includes: "**/*",
cacheValidityDecidingFile: "package-lock.json"
)
]) {
sh "npm install"
}
}
}
stage("Build") {
steps {
// 基于 GIT_COMMIT 哈希将锁文件写入缓存
writeFile file: "next-lock.cache", text: "$GIT_COMMIT"
cache(caches: [
arbitraryFileCache(
path: ".next/cache",
includes: "**/*",
cacheValidityDecidingFile: "next-lock.cache"
)
]) {
// 即 `next build`
sh "npm run build"
}
}
}