跳至內容

最佳化打包 (Optimizing Bundling)

打包外部套件可以顯著提升應用程式的效能。(Bundling external packages can significantly improve the performance of your application.) 預設情況下,導入至應用程式的套件不會被打包。這可能會影響效能,或者如果外部套件未預先打包,例如從 monorepo 或 node_modules 導入,則可能無法正常運作。本頁面將引導您如何分析和設定套件打包。(By default, packages imported into your application are not bundled. This can impact performance or might not work if external packages are not pre-bundled, for example, if imported from a monorepo or node_modules. This page will guide you through how to analyze and configure package bundling.)

分析 JavaScript 套件

@next/bundle-analyzer 是一個 Next.js 的插件,可以幫助您管理應用程式套件的大小。它會產生一份視覺化報告,顯示每個套件及其相依套件的大小。您可以使用這些資訊來移除大型相依套件、分割程式碼或延遲載入您的程式碼。

安裝

執行以下指令來安裝插件:

npm i @next/bundle-analyzer
# or
yarn add @next/bundle-analyzer
# or
pnpm add @next/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

報告將會在您的瀏覽器中開啟三個新的分頁,您可以檢查這些分頁。定期評估應用程式的套件可以幫助您隨著時間推移維持應用程式的效能。

最佳化套件導入
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

後續步驟 (Next Steps)

深入瞭解如何最佳化您的應用程式以進行生產。