持續整合 (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/**/*' # 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` https://github.com/actions/cache/blob/main/examples.md#node---yarn 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 的 快取工作,在執行 next build
的工作之前的某處,將以下工作新增至您的 pipeline 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 外掛程式,將以下建置步驟新增至您通常會執行 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"
}
}
}
這有幫助嗎?