持续集成 (CI) 构建缓存

为提升构建性能,Next.js 会将缓存保存至 .next/cache 目录,这些缓存可在不同构建间共享。

要在持续集成 (CI) 环境中利用此缓存,您需要配置 CI 工作流以确保缓存能在构建间正确保留。

若未配置 CI 保留 .next/cache 目录中的缓存,您可能会遇到 未检测到缓存 错误。

以下是常见 CI 提供商的缓存配置示例:

Vercel

Next.js 缓存已自动配置完成,您无需进行任何操作。

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@v3
with:
  # 关于 `yarn` 的缓存配置参见 https://github.com/actions/cache/blob/main/examples.md#node---yarn 或使用 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

然后在流水线步骤的 caches 部分引用该缓存:

- step:
    name: your_step_name
    caches:
      - node
      - nextcache

Heroku

使用 Heroku 的 自定义缓存,在顶层 package.json 中添加 cacheDirectories 数组:

"cacheDirectories": [".next/cache"]

Azure Pipelines

使用 Azure Pipelines 的 缓存任务,在执行 next build 的任务之前添加以下任务到流水线 yaml 文件:

- task: Cache@2
  displayName: '缓存 .next/cache'
  inputs:
    key: next | $(Agent.OS) | yarn.lock
    path: '$(System.DefaultWorkingDirectory)/.next/cache'