优化打包
打包外部包可以显著提高你的应用程序的性能。 默认情况下,导入到你的应用程序中的包不会被打包。如果外部包没有预先打包,例如,从 monorepo 或 node_modules
导入,这可能会影响性能或无法正常工作。本页将指导你如何分析和配置包打包。
分析 JavaScript 包
@next/bundle-analyzer
是一个 Next.js 插件,可帮助你管理应用程序包的大小。它生成每个包及其依赖项大小的可视化报告。你可以使用这些信息来删除大型依赖项、拆分或 lazy-load 你的代码。
安装
运行以下命令安装插件
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
这篇文章对您有帮助吗?