持續整合 (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
然後在您 pipeline 的 step
中的 caches
區段中參考它
- step:
name: your_step_name
caches:
- node
- nextcache
Heroku
使用 Heroku 的 自訂快取,在您的頂層 package.json 中新增 cacheDirectories
陣列
"cacheDirectories": [".next/cache"]
Azure Pipelines
使用 Azure Pipelines 的 快取任務,在您的 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 插件,在您的 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"
}
}
}
這對您有幫助嗎?