优化打包
捆绑外部包可以显著提高应用程序的性能。 默认情况下,导入到应用程序中的包不会被捆绑。如果外部包未预先捆绑,例如从 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
。
/** @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
来优化这些包的导入方式。此选项将仅加载您实际使用的模块,同时仍然为您提供编写具有许多命名导出的导入语句的便利。
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
optimizePackageImports: ['icon-library'],
},
}
module.exports = nextConfig
Next.js 还会自动优化某些库,因此它们不需要包含在 optimizePackageImports 列表中。请参阅完整列表。
打包特定包
要捆绑特定包,您可以使用 next.config.js
中的 transpilePackages
选项。此选项对于捆绑未预先捆绑的外部包非常有用,例如,在 monorepo 中或从 node_modules
导入的包。
/** @type {import('next').NextConfig} */
const nextConfig = {
transpilePackages: ['package-name'],
}
module.exports = nextConfig
打包所有包
要自动捆绑所有包(App Router 中的默认行为),您可以使用 next.config.js
中的 bundlePagesRouterDependencies
选项。
/** @type {import('next').NextConfig} */
const nextConfig = {
bundlePagesRouterDependencies: true,
}
module.exports = nextConfig
选择不打包特定包
如果您启用了 bundlePagesRouterDependencies
选项,则可以使用 next.config.js
中的 serverExternalPackages
选项选择不自动捆绑特定包。
/** @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
这有帮助吗?