如何配置持续集成(CI)构建缓存
了解如何配置 CI 以缓存 Next.js 构建
为了提升构建性能,Next.js 会将缓存保存到 .next/cache,并在多次构建之间共享。
要在持续集成(CI)环境中利用此缓存,你需要配置 CI 工作流,使其能在多次构建之间正确保留该缓存。
如果你的 CI 未配置为在多次构建之间保留
.next/cache,你可能会看到 No Cache Detected 错误。
以下是一些常见 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/**/*' # Cache `node_modules` for faster `yarn` or `npm i`
- '.next/cache/**/*' # Cache Next.js for faster application rebuilds
GitHub Actions
使用 GitHub 的 actions/cache,在你的工作流文件中添加以下步骤:
uses: actions/cache@v4
with:
# See here for caching with `yarn`, `bun` or other package managers https://github.com/actions/cache/blob/main/examples.md or you can leverage caching with actions/setup-node https://github.com/actions/setup-node
path: |
~/.npm
${{ github.workspace }}/.next/cache
# Generate a new cache whenever packages or source files change.
key: ${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json') }}-${{ hashFiles('**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx') }}
# If source files changed but packages didn't, rebuild from a prior cache.
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 task,在 pipeline YAML 文件中,将以下任务添加到执行 next build 的任务之前的某个位置:
- task: Cache@2
displayName: 'Cache .next/cache'
inputs:
key: next | $(Agent.OS) | yarn.lock
path: '$(System.DefaultWorkingDirectory)/.next/cache'
Jenkins(Pipeline)
使用 Jenkins 的 Job Cacher 插件,在通常运行 next build 或 npm install 的 Jenkinsfile 中添加以下构建步骤:
stage("Restore npm packages") {
steps {
// Writes lock-file to cache based on the GIT_COMMIT hash
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 {
// Writes lock-file to cache based on the GIT_COMMIT hash
writeFile file: "next-lock.cache", text: "$GIT_COMMIT"
cache(caches: [
arbitraryFileCache(
path: ".next/cache",
includes: "**/*",
cacheValidityDecidingFile: "next-lock.cache"
)
]) {
// aka `next build`
sh "npm run build"
}
}
}