-
Notifications
You must be signed in to change notification settings - Fork 29.9k
Introduce next analyze: a built-in bundle analyzer for Turbopack
#85915
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -210,6 +210,7 @@ | |
| "@types/react-is": "18.2.4", | ||
| "@types/semver": "7.3.1", | ||
| "@types/send": "0.14.4", | ||
| "@types/serve-handler": "6.1.4", | ||
| "@types/shell-quote": "1.7.1", | ||
| "@types/tar": "6.1.5", | ||
| "@types/text-table": "0.2.1", | ||
|
|
@@ -315,6 +316,7 @@ | |
| "schema-utils3": "npm:[email protected]", | ||
| "semver": "7.3.2", | ||
| "send": "0.18.0", | ||
| "serve-handler": "6.1.6", | ||
| "server-only": "0.0.1", | ||
| "setimmediate": "1.0.5", | ||
| "shell-quote": "1.7.3", | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,249 @@ | ||
| import type { NextConfigComplete } from '../../server/config-shared' | ||
| import type { __ApiPreviewProps } from '../../server/api-utils' | ||
|
|
||
| import { setGlobal } from '../../trace' | ||
| import * as Log from '../output/log' | ||
| import * as path from 'node:path' | ||
| import loadConfig from '../../server/config' | ||
| import { PHASE_ANALYZE } from '../../shared/lib/constants' | ||
| import { turbopackAnalyze, type AnalyzeContext } from '../turbopack-analyze' | ||
| import { durationToString } from '../duration-to-string' | ||
| import { cp, writeFile, mkdir } from 'node:fs/promises' | ||
| import { | ||
| collectAppFiles, | ||
| collectPagesFiles, | ||
| createPagesMapping, | ||
| } from '../entries' | ||
| import { createValidFileMatcher } from '../../server/lib/find-page-file' | ||
| import { findPagesDir } from '../../lib/find-pages-dir' | ||
| import { PAGE_TYPES } from '../../lib/page-types' | ||
| import loadCustomRoutes from '../../lib/load-custom-routes' | ||
| import { generateRoutesManifest } from '../generate-routes-manifest' | ||
| import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr' | ||
| import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' | ||
| import http from 'node:http' | ||
|
|
||
| // @ts-expect-error types are in @types/serve-handler | ||
| import serveHandler from 'next/dist/compiled/serve-handler' | ||
| import { Telemetry } from '../../telemetry/storage' | ||
| import { eventAnalyzeCompleted } from '../../telemetry/events' | ||
| import { traceGlobals } from '../../trace/shared' | ||
| import type { RoutesManifest } from '..' | ||
|
|
||
| const ANALYZE_PATH = '.next/diagnostics/analyze' | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Path needs to respect |
||
|
|
||
| export type AnalyzeOptions = { | ||
| dir: string | ||
| reactProductionProfiling?: boolean | ||
| noMangling?: boolean | ||
| appDirOnly?: boolean | ||
| serve?: boolean | ||
| port?: number | ||
| } | ||
|
|
||
| export default async function analyze({ | ||
| dir, | ||
| reactProductionProfiling = false, | ||
| noMangling = false, | ||
| appDirOnly = false, | ||
wbinnssmith marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| serve = false, | ||
| port = 4000, | ||
| }: AnalyzeOptions): Promise<void> { | ||
| try { | ||
| const config: NextConfigComplete = await loadConfig(PHASE_ANALYZE, dir, { | ||
| silent: false, | ||
| reactProductionProfiling, | ||
| }) | ||
|
|
||
| process.env.NEXT_DEPLOYMENT_ID = config.deploymentId || '' | ||
|
|
||
| const distDir = path.join(dir, '.next') | ||
| const telemetry = new Telemetry({ distDir }) | ||
| setGlobal('phase', PHASE_ANALYZE) | ||
| setGlobal('distDir', distDir) | ||
| setGlobal('telemetry', telemetry) | ||
|
|
||
| Log.info('Analyzing a production build...') | ||
|
|
||
| const analyzeContext: AnalyzeContext = { | ||
| config, | ||
| dir, | ||
| distDir, | ||
| noMangling, | ||
| appDirOnly, | ||
| } | ||
|
|
||
| const { duration: analyzeDuration, shutdownPromise } = | ||
| await turbopackAnalyze(analyzeContext) | ||
|
|
||
| const durationString = durationToString(analyzeDuration) | ||
| Log.event( | ||
| `Analyze data created successfully in ${durationString}. To explore it, run \`next experimental-analyze --serve\`.` | ||
| ) | ||
|
|
||
| await shutdownPromise | ||
|
|
||
| await cp( | ||
| path.join(__dirname, '../../bundle-analyzer'), | ||
| path.join(dir, ANALYZE_PATH), | ||
| { recursive: true } | ||
| ) | ||
|
|
||
| // Collect and write routes for the bundle analyzer | ||
| const routes = await collectRoutesForAnalyze(dir, config, appDirOnly) | ||
|
|
||
| await mkdir(path.join(dir, ANALYZE_PATH, 'data'), { recursive: true }) | ||
| await writeFile( | ||
| path.join(dir, ANALYZE_PATH, 'data', 'routes.json'), | ||
| JSON.stringify(routes, null, 2) | ||
| ) | ||
|
|
||
| telemetry.record( | ||
| eventAnalyzeCompleted({ | ||
| success: true, | ||
| durationInSeconds: Math.round(analyzeDuration), | ||
| totalPageCount: routes.length, | ||
| }) | ||
| ) | ||
|
|
||
| if (serve) { | ||
| await startServer(path.join(dir, ANALYZE_PATH), port) | ||
| } | ||
| } catch (e) { | ||
| const telemetry = traceGlobals.get('telemetry') as Telemetry | undefined | ||
| if (telemetry) { | ||
| telemetry.record( | ||
| eventAnalyzeCompleted({ | ||
| success: false, | ||
| }) | ||
| ) | ||
| } | ||
|
|
||
| throw e | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Collects all routes from the project for the bundle analyzer. | ||
| * Returns a list of route paths (both static and dynamic). | ||
| */ | ||
| async function collectRoutesForAnalyze( | ||
| dir: string, | ||
| config: NextConfigComplete, | ||
| appDirOnly: boolean | ||
| ): Promise<string[]> { | ||
| const { pagesDir, appDir } = findPagesDir(dir) | ||
| const validFileMatcher = createValidFileMatcher(config.pageExtensions, appDir) | ||
|
|
||
| let appType: RoutesManifest['appType'] | ||
| if (pagesDir && appDir) { | ||
| appType = 'hybrid' | ||
| } else if (pagesDir) { | ||
| appType = 'pages' | ||
| } else if (appDir) { | ||
| appType = 'app' | ||
| } else { | ||
| throw new Error('No pages or app directory found.') | ||
| } | ||
|
|
||
| const { appPaths } = appDir | ||
| ? await collectAppFiles(appDir, validFileMatcher) | ||
| : { appPaths: [] } | ||
| const pagesPaths = pagesDir | ||
| ? await collectPagesFiles(pagesDir, validFileMatcher) | ||
| : null | ||
|
|
||
| const appMapping = await createPagesMapping({ | ||
| pagePaths: appPaths, | ||
| isDev: false, | ||
| pagesType: PAGE_TYPES.APP, | ||
| pageExtensions: config.pageExtensions, | ||
| pagesDir, | ||
| appDir, | ||
| appDirOnly, | ||
| }) | ||
|
|
||
| const pagesMapping = pagesPaths | ||
| ? await createPagesMapping({ | ||
| pagePaths: pagesPaths, | ||
| isDev: false, | ||
| pagesType: PAGE_TYPES.PAGES, | ||
| pageExtensions: config.pageExtensions, | ||
| pagesDir, | ||
| appDir, | ||
| appDirOnly, | ||
| }) | ||
| : null | ||
|
|
||
| const pageKeys = { | ||
| pages: pagesMapping ? Object.keys(pagesMapping) : [], | ||
| app: appMapping | ||
| ? Object.keys(appMapping).map((key) => normalizeAppPath(key)) | ||
| : undefined, | ||
| } | ||
|
|
||
| // Load custom routes | ||
| const { redirects, headers, rewrites } = await loadCustomRoutes(config) | ||
|
|
||
| // Compute restricted redirect paths | ||
| const restrictedRedirectPaths = ['/_next'].map((pathPrefix) => | ||
| config.basePath ? `${config.basePath}${pathPrefix}` : pathPrefix | ||
| ) | ||
|
|
||
| const isAppPPREnabled = checkIsAppPPREnabled(config.experimental.ppr) | ||
|
|
||
| // Generate routes manifest | ||
| const { routesManifest } = generateRoutesManifest({ | ||
| appType, | ||
| pageKeys, | ||
| config, | ||
| redirects, | ||
| headers, | ||
| rewrites, | ||
| restrictedRedirectPaths, | ||
| isAppPPREnabled, | ||
| }) | ||
|
|
||
| return routesManifest.dynamicRoutes | ||
| .map((r) => r.page) | ||
| .concat(routesManifest.staticRoutes.map((r) => r.page)) | ||
| } | ||
|
|
||
| function startServer(dir: string, port: number): Promise<void> { | ||
| const server = http.createServer((req, res) => { | ||
| return serveHandler(req, res, { | ||
| public: dir, | ||
| }) | ||
| }) | ||
|
|
||
| return new Promise((resolve, reject) => { | ||
| function onError(err: Error) { | ||
| server.close(() => { | ||
| reject(err) | ||
| }) | ||
| } | ||
|
|
||
| server.on('error', onError) | ||
|
|
||
| server.listen(port, 'localhost', () => { | ||
| const address = server.address() | ||
| if (address == null) { | ||
| reject(new Error('Unable to get server address')) | ||
| return | ||
| } | ||
|
|
||
| // No longer needed after startup | ||
| server.removeListener('error', onError) | ||
|
|
||
| let addressString | ||
| if (typeof address === 'string') { | ||
| addressString = address | ||
| } else { | ||
| addressString = `${address.address === '::' ? 'localhost' : address.address}:${address.port}` | ||
wbinnssmith marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| Log.info(`Bundle analyzer available at http://${addressString}`) | ||
| resolve() | ||
wbinnssmith marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| }) | ||
| }) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Does it make sense to have a
--no-buildoption in case you already built with all the right flags to emit the analyzer output?Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The problem with this is that would make
next analyze --no-builda no-op without also doingnext analyze --no-build --serveAlternatively, we could do optional subcommands:
next analyze-- does bothnext analyze build-- only does buildnext analyze serve-- only does serveOr similarly, we make
next analyzedefault to both and havenext analyze-- does bothnext analyze --no-serve-- only does buildnext analyze --no-build-- only does serve