How to configure Continuous Integration (CI) build caching
为了提高构建性能,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 Plugins 和 @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 的 Cache 任务,在执行 next build
任务之前的某处,将以下任务添加到你的流水线 yaml 文件中:
- task: Cache@2
displayName: 'Cache .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"
}
}
}