如何分析Next.js應用程序捆綁包

了解有關Next.js應用程序捆綁中的內容的更多信息

Next為我們提供了一種分析生成的代碼包的方法。

打開應用程序的package.json文件,然後在腳本部分中添加這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"
  }
}

然後安裝這兩個軟件包:

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({})

現在運行命令

npm run analyze

這將在瀏覽器中打開2個頁面。一種用於客戶端捆綁,另一種用於服務器捆綁:

這是非常有用的。您可以檢查束中佔用最多空間的空間,還可以使用邊欄排除束,以更輕鬆地可視化較小的束:

免費下載我的Next.js手冊


接下來的更多教程: