如何優化套件打包

打包外部套件能顯著提升應用程式效能。 預設情況下,導入應用程式的套件不會被打包。這可能影響效能,或導致外部套件無法運作(例如從 monorepo 或 node_modules 導入的套件若未預先打包)。本頁將引導您如何分析與設定套件打包。

分析 JavaScript 套件包

@next/bundle-analyzer 是 Next.js 的插件,可協助管理應用程式套件包大小。它會生成每個套件及其依賴項大小的視覺化報告,您可據此移除大型依賴、拆分程式碼或進行懶加載 (lazy-loading)

安裝

執行以下指令安裝插件:

npm i @next/bundle-analyzer
# 或
yarn add @next/bundle-analyzer
# 或
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
# 或
ANALYZE=true yarn build
# 或
ANALYZE=true pnpm build

報告將在瀏覽器開啟三個新分頁供您檢視。定期評估應用程式套件包有助於長期維持效能。

優化套件導入

某些套件(如圖示庫)可能導出數百個模組,導致開發與生產環境的效能問題。

您可透過在 next.config.js 加入 optimizePackageImports 選項來優化導入方式。此選項僅載入實際使用的模組,同時保留使用多個命名導入的便利性。

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.jsserverExternalPackages 選項排除特定套件不自動打包:

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  // 在 Pages Router 自動打包外部套件:
  bundlePagesRouterDependencies: true,
  // 為 App 和 Pages Router 排除特定套件不打包:
  serverExternalPackages: ['package-name'],
}

module.exports = nextConfig

On this page