跳到内容

如何优化包捆绑

捆绑外部包可以显著提高应用程序的性能。 默认情况下,导入到应用程序中的包不会被捆绑。这可能会影响性能,或者在外部包未预先捆绑的情况下可能无法工作,例如,如果从 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

然后,将捆绑分析器的设置添加到您的 `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` 中添加 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.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

下一步

了解更多关于优化您的应用程序以进行生产的信息。