如何分析 Next.js 應用程式的捆綁檔案 深入了解 Next.js 應用程式捆綁檔案內容的方法。
Next.js 提供了一種分析產生程式碼捆綁檔案的方式。
打開專案的 package.json 檔案,並在 scripts 區塊中新增以下三個指令:
1 2 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"
就像這樣:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 { "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" } }
然後安裝下列兩個套件:
1 npm install --dev cross-env @next/bundle-analyzer
在專案根目錄下創建 next.config.js
檔案,並加入以下內容:
1 2 3 4 5 const withBundleAnalyzer = require('@next/bundle-analyzer')({ enabled: process.env.ANALYZE === 'true' }) module.exports = withBundleAnalyzer({})
現在執行以下指令:
這應該會在瀏覽器中打開兩個頁面,一個用於客戶端捆綁檔案,另一個用於服務器捆綁檔案:
這非常有用。您可以檢查捆綁檔案中佔用空間最多的內容,並使用側邊欄來排除某些捆綁檔案,以便更容易地可視化較小的檔案:
tags: [“Next.js”, “bundle analysis”, “optimization”]