如何分析Next.js的应用程序捆绑包

699 阅读1分钟

了解更多关于Next.js应用包中的内容

Next为我们提供了一种分析生成的代码包的方法。

打开应用程序的package.json文件,在scripts部分添加这3条新命令。

"analyze": "cross-env ANALYZE=true next build",
"analyze:server": "cross-env BUNDLE_ANALYZE=server next build",
"analyze:browser": "cross-env BUNDLE_ANALYZE=browser next build"

像这样。

{
  "name": "firstproject",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start",
    "analyze": "cross-env ANALYZE=true next build",
    "analyze:server": "cross-env BUNDLE_ANALYZE=server next build",
    "analyze:browser": "cross-env BUNDLE_ANALYZE=browser next build"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "next": "^9.1.2",
    "react": "^16.11.0",
    "react-dom": "^16.11.0"
  }
}

然后安装这2个包。

npm install --dev cross-env @next/bundle-analyzer

在项目根目录下创建一个next.config.js 文件,内容是这样的。

const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true'
})

module.exports = withBundleAnalyzer({})

现在运行该命令

这应该在浏览器中打开2个页面。一个是客户捆绑包,一个是服务器捆绑包。

这是很有用的。你可以检查哪些东西在捆绑程序中占用了最多的空间,你也可以使用侧边栏排除捆绑程序,以便更容易看到较小的程序。