为了提高构建性能,Next.js 会将一个缓存在 .next/cache 目录下,该缓存可在不同构建之间共享。
为了在持续集成 (CI) 环境中利用此缓存,您的 CI 工作流需要配置为在不同构建之间正确地持久化该缓存。
如果您的 CI 未配置为在构建之间持久化
.next/cache,您可能会看到一个 No Cache Detected 错误。
以下是一些常见 CI 提供商的缓存配置示例:
Next.js 缓存已为您自动配置。您无需进行任何操作。如果您在 Vercel 上使用 Turborepo,请在此处了解更多信息。
编辑您在 .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.yml 中:
cache:
directories:
- $HOME/.cache/yarn
- node_modules
- .next/cache将以下内容添加或合并到您的 .gitlab-ci.yml 中:
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/
- .next/cache/使用 Netlify Plugins 配合 @netlify/plugin-nextjs。
将以下内容添加(或合并)到您的 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/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.yml 的顶层(与 pipelines 处于同一级别)添加或合并以下内容:
definitions:
caches:
nextcache: .next/cache然后在您的管道的 step 的 caches 部分引用它:
- step:
name: your_step_name
caches:
- node
- nextcache使用 Heroku 的 自定义缓存 功能,在您的顶级 package.json 中添加一个 cacheDirectories 数组:
"cacheDirectories": [".next/cache"]使用 Azure Pipelines 的 缓存任务,在执行 next build 任务之前的某个位置,将以下任务添加到您的管道 YAML 文件中:
- task: Cache@2
displayName: 'Cache .next/cache'
inputs:
key: next | $(Agent.OS) | yarn.lock
path: '$(System.DefaultWorkingDirectory)/.next/cache'使用 Jenkins 的 Job Cacher 插件,将以下构建步骤添加到您的 Jenkinsfile 中,通常是您运行 next build 或 npm install 的位置:
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"
}
}
}