跳到內容

最佳化打包

打包外部套件可以顯著提升你的應用程式效能。 預設情況下,匯入到你的應用程式中的套件不會被打包。如果外部套件未預先打包,例如從 monorepo 或 node_modules 匯入,這可能會影響效能或無法運作。本頁面將引導你如何分析和設定套件打包。

分析 JavaScript 打包

@next/bundle-analyzer 是一個 Next.js 的外掛程式,可協助你管理應用程式打包的大小。它會產生每個套件及其依賴關係大小的可視化報告。你可以使用這些資訊來移除大型依賴關係、分割或延遲載入你的程式碼。

安裝

執行以下命令來安裝此外掛程式

npm i @next/bundle-analyzer
# or
yarn add @next/bundle-analyzer
# or
pnpm add @next/bundle-analyzer

然後,將 bundle analyzer 的設定新增到你的 next.config.js

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {}
 
const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
})
 
module.exports = withBundleAnalyzer(nextConfig)

產生報告

執行以下命令來分析你的打包

ANALYZE=true npm run build
# or
ANALYZE=true yarn build
# or
ANALYZE=true pnpm build

報告將在你的瀏覽器中開啟三個新的分頁,你可以檢查這些分頁。定期評估你的應用程式打包可以幫助你長期維持應用程式效能。

最佳化套件匯入

某些套件,例如圖示函式庫,可以匯出數百個模組,這可能會在開發和生產環境中造成效能問題。

你可以透過將 optimizePackageImports 選項新增到你的 next.config.js 來最佳化這些套件的匯入方式。此選項只會載入你實際使用的模組,同時仍為你提供編寫具有許多具名匯出項的匯入語句的便利性。

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    optimizePackageImports: ['icon-library'],
  },
}
 
module.exports = nextConfig

Next.js 也會自動最佳化某些函式庫,因此它們不需要包含在 optimizePackageImports 清單中。請參閱完整清單

打包特定套件

若要打包特定套件,你可以使用 next.config.js 中的 transpilePackages 選項。此選項適用於打包未預先打包的外部套件,例如在 monorepo 中或從 node_modules 匯入的套件。

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  transpilePackages: ['package-name'],
}
 
module.exports = nextConfig

打包所有套件

若要自動打包所有套件(App Router 中的預設行為),你可以使用 next.config.js 中的 bundlePagesRouterDependencies 選項。

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  bundlePagesRouterDependencies: true,
}
 
module.exports = nextConfig

選擇不打包特定套件

如果你已啟用 bundlePagesRouterDependencies 選項,你可以使用 next.config.js 中的 serverExternalPackages 選項,選擇不自動打包特定套件

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  // Automatically bundle external packages in the Pages Router:
  bundlePagesRouterDependencies: true,
  // Opt specific packages out of bundling for both App and Pages Router:
  serverExternalPackages: ['package-name'],
}
 
module.exports = nextConfig