Skip to main content

打包分析器

@next/bundle-analyzer 是 Next.js 的一个插件,可帮助你管理 JavaScript 模块的大小。它生成每个模块的大小及其依赖的可视化报告。你可以使用这些信息来删除较大的依赖、拆分代码或仅在需要时加载某些部分,从而减少传输到客户端的数据量。

¥@next/bundle-analyzer is a plugin for Next.js that helps you manage the size of your JavaScript modules. It generates a visual report of the size of each module and their dependencies. You can use the information to remove large dependencies, split your code, or only load some parts when needed, reducing the amount of data transferred to the client.

安装

¥Installation

通过运行以下命令安装插件:

¥Install the plugin by running the following command:

npm i @next/bundle-analyzer
# or
yarn add @next/bundle-analyzer
# or
pnpm add @next/bundle-analyzer

然后,将打包分析器的设置添加到你的 next.config.js

¥Then, add the bundle analyzer's settings to your next.config.js.

/** @type {import('next').NextConfig} */
const nextConfig = {}

const withBundleAnalyzer = require('@next/bundle-analyzer')()

module.exports =
process.env.ANALYZE === 'true' ? withBundleAnalyzer(nextConfig) : nextConfig

分析你的打包

¥Analyzing your bundles

运行以下命令来分析你的包:

¥Run the following command to analyze your bundles:

ANALYZE=true npm run build
# or
ANALYZE=true yarn build
# or
ANALYZE=true pnpm build

该报告将在你的浏览器中打开三个新选项卡,你可以检查这些选项卡。在开发时和部署站点之前定期执行此操作可以帮助你更早地识别大型打包包,并构建应用以提高性能。

¥The report will open three new tabs in your browser, which you can inspect. Doing this regularly while you develop and before deploying your site can help you identify large bundles earlier, and architect your application to be more performant.