From aaa5fefdf74dc49b69532615b6721aa8957b3d0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Chopin?= Date: Sun, 8 Nov 2026 07:55:36 +0000 Subject: [PATCH] feat(build): summarise the client bundle at the end of `nuxt build` Amp-Thread-ID: https://ampcode.com/threads/T-01a1ba1d-4162-7728-8948-c39866ce9567 --- packages/nuxt-cli/src/commands/build.ts | 20 +- packages/nuxt-cli/src/utils/client-bundle.ts | 670 ++++++++++++++++++ packages/nuxt-cli/src/utils/logger.ts | 18 +- .../nuxt-cli/test/unit/client-bundle.spec.ts | 498 +++++++++++++ .../nuxt-cli/test/unit/commands/build.spec.ts | 1 + .../nuxt-cli/test/unit/utils/logger.spec.ts | 25 +- 6 files changed, 1229 insertions(+), 3 deletions(-) create mode 100644 packages/nuxt-cli/src/utils/client-bundle.ts create mode 100644 packages/nuxt-cli/test/unit/client-bundle.spec.ts diff --git a/packages/nuxt-cli/src/commands/build.ts b/packages/nuxt-cli/src/commands/build.ts index 9647b4c06..50dffcb2d 100644 --- a/packages/nuxt-cli/src/commands/build.ts +++ b/packages/nuxt-cli/src/commands/build.ts @@ -16,7 +16,7 @@ import { formatDuration } from '../utils/formatting' import { clearBuildDir } from '../utils/fs' import { loadKit } from '../utils/kit' import { acquireLock, acquireOutputLock, formatLockError } from '../utils/lockfile' -import { intro, logger, outro } from '../utils/logger' +import { intro, logBlock, logger, outro } from '../utils/logger' import { resolveRootDir } from '../utils/paths' import { createPhaseReporter, formatPhaseBreakdown, formatPhaseTable } from '../utils/phase-reporter' import { startCpuProfile, stopCpuProfile } from '../utils/profile' @@ -118,6 +118,12 @@ export default defineCommand({ progress, command: ctx.args.prerender ? 'generate' : 'build', }) + // Imported here rather than at the top so that commands which only load + // this file, such as `nuxt --help`, don't load the summary with it. + const { collectClientBundle, dedupeCommandFor, formatClientBundle } = await import('../utils/client-bundle') + const clientBundle = nuxt.options.logLevel === 'silent' + ? undefined + : collectClientBundle(nuxt) showBanner(nuxt) await nuxt.ready() @@ -159,6 +165,18 @@ export default defineCommand({ progress.finish() const elapsed = Date.now() - start + const bundle = clientBundle?.() + if (bundle) { + logBlock(formatClientBundle(bundle, { + // Clack's gutter takes three columns of every row in a terminal. + columns: (process.stdout.columns || 80) - 3, + projectDir: relative(process.cwd(), nuxt.options.rootDir), + dedupeCommand: bundle.duplicates.length + ? await dedupeCommandFor(nuxt.options.rootDir) + : undefined, + })) + } + const verbose = nuxt.options.logLevel === 'verbose' const summary = nuxt.options.logLevel === 'silent' ? undefined diff --git a/packages/nuxt-cli/src/utils/client-bundle.ts b/packages/nuxt-cli/src/utils/client-bundle.ts new file mode 100644 index 000000000..fb7d64421 --- /dev/null +++ b/packages/nuxt-cli/src/utils/client-bundle.ts @@ -0,0 +1,670 @@ +import type { Nuxt } from '@nuxt/schema' + +import { Buffer } from 'node:buffer' +import { readFileSync } from 'node:fs' +import { styleText } from 'node:util' +import { gzipSync } from 'node:zlib' + +import { join, relative } from 'pathe' + +import { formatBytes, visibleWidth, wrapText } from './formatting' +import { detectPackageManager } from './package-managers' + +/** A JavaScript or CSS file of the client build, as Rolldown wrote it. */ +export interface ClientFile { + fileName: string + kind: 'js' | 'css' + size: number + gzip: number + isEntry: boolean + isDynamicEntry: boolean + /** The module the chunk is named after, such as the page or component it lazy loads. */ + source?: string + imports: string[] + css: string[] + /** Assets the chunk references by URL, such as a stylesheet imported with `?url`. */ + assets: string[] + /** What the chunk is made of, as a share of its final size. */ + modules: Array<{ id: string, size: number, importers: string[] }> +} + +/** Where a module comes from: an npm package, the app itself, or a module Nuxt or Vite generate. */ +interface Origin { + kind: 'package' | 'app' | 'virtual' + name: string + /** Directory the package is installed in, which tells two copies of it apart. */ + dir?: string +} + +interface BundleGroup { + name: string + kind: Origin['kind'] | 'framework' | 'css' + size: number +} + +export interface BundleSummary { + /** JavaScript and CSS, what the bar shares out. */ + size: number + initial: { size: number, gzip: number } + /** Page routes, when the app uses pages. */ + routes?: number + /** What the bundle is made of, largest first: the framework, packages, the app and its CSS. */ + groups: BundleGroup[] + duplicates: Array<{ name: string, copies: Array<{ version?: string, importedBy: string[] }> }> + /** App data files bundled into JavaScript, which every visit downloads and parses again. */ + data: Array<{ file: string, size: number, importedBy: string[] }> +} + +const NODE_MODULES = '/node_modules/' +const APP_GROUP = 'your app' +const FRAMEWORK_GROUP = 'Nuxt & Vue' +const CSS_GROUP = 'CSS' +/** App files that are data rather than code, and better fetched than bundled. */ +const DATA_RE = /\.json5?$/ +const LARGE_DATA = 100_000 +/** Gzipped bytes every page can load before the summary suggests lazy loading. */ +const INITIAL_BUDGET = 200_000 +/** The framework every Nuxt app ships; packages only it imports join it. */ +const FRAMEWORK_RE = /^(?:nuxt|nuxt-nightly|vue|vue-router|unhead|@vue\/.*|@unhead\/.*)$/ +/** Nuxt's app entry, which `experimental.asyncEntry` loads with a dynamic import. */ +const APP_ENTRY_RE = /\/nuxt(?:-nightly)?\/dist\/app\/entry\.m?js$/ +const QUERY_RE = /\?.*$/ +const PACKAGE_NAME_RE = /^(@[^/]+\/[^/]+|[^/]+)/ + +function originOf(id: string, rootDir: string): Origin { + if (id.startsWith('\0') || id.startsWith('virtual:') || id.includes('/.nuxt/')) { + return { kind: 'virtual', name: 'virtual modules' } + } + const path = id.replace(QUERY_RE, '') + const index = path.lastIndexOf(NODE_MODULES) + if (index !== -1) { + const name = path.slice(index + NODE_MODULES.length).match(PACKAGE_NAME_RE)?.[1] + if (name) { + return { kind: 'package', name, dir: path.slice(0, index + NODE_MODULES.length) + name } + } + } + return { + kind: 'app', + name: relative(rootDir, path), + } +} + +/** + * What imports a module's package from outside it, looking through the + * package's own files: an entry that only re-exports leaves the bundle, and + * with it the link to whatever imported the package. + */ +export function outsideImporters(id: string, rootDir: string, importersOf: (id: string) => readonly string[]): string[] { + const dir = originOf(id, rootDir).dir + if (!dir) { + return [ + ...importersOf(id), + ] + } + const found = new Set() + const seen = new Set([id]) + const queue = [ + ...importersOf(id), + ] + while (queue.length) { + const next = queue.pop()! + if (seen.has(next)) { + continue + } + seen.add(next) + if (originOf(next, rootDir).dir === dir) { + queue.push(...importersOf(next)) + } + else { + found.add(next) + } + } + return [...found] +} + +interface RolldownChunk { + type: 'chunk' + fileName: string + code: string + isEntry: boolean + isDynamicEntry: boolean + facadeModuleId: string | null + imports: string[] + modules: Record + viteMetadata?: { importedCss: Set, importedAssets: Set } +} + +interface RolldownAsset { + type: 'asset' + fileName: string + source: string | Uint8Array +} + +function byteLength(content: string | Uint8Array): number { + return typeof content === 'string' + ? Buffer.byteLength(content) + : content.byteLength +} + +/** + * Read the client build out of the bundle Rolldown is about to write. Module + * sizes are measured before minification, so each one is scaled to its share + * of the chunk's final size: close enough to rank what a chunk is made of. + */ +export function readClientBundle(bundle: Record, getImporters: (id: string) => readonly string[] = () => []): ClientFile[] { + const files: ClientFile[] = [] + for (const output of Object.values(bundle)) { + if (output.type === 'chunk') { + const size = byteLength(output.code) + // Modules that render to nothing are kept: a package's entry is often only + // re-exports, and it is the one the app imports. + const rendered = Object.entries(output.modules) + const total = rendered.reduce((sum, [, module]) => sum + module.renderedLength, 0) + files.push({ + fileName: output.fileName, + kind: 'js', + size, + gzip: gzipSync(output.code).byteLength, + isEntry: output.isEntry, + isDynamicEntry: output.isDynamicEntry, + source: output.facadeModuleId ?? undefined, + imports: output.imports, + css: [ + ...output.viteMetadata?.importedCss ?? [], + ], + assets: [ + ...output.viteMetadata?.importedAssets ?? [], + ], + modules: rendered.map(([id, module]) => ({ + id, + size: total + ? module.renderedLength / total * size + : 0, + importers: [ + ...getImporters(id), + ], + })), + }) + } + else if (output.fileName.endsWith('.css')) { + files.push({ + fileName: output.fileName, + kind: 'css', + size: byteLength(output.source), + gzip: gzipSync(output.source).byteLength, + isEntry: false, + isDynamicEntry: false, + imports: [], + css: [], + assets: [], + modules: [], + }) + } + } + return files +} + +/** + * The files every page loads: the entry and Nuxt's app entry, which + * `experimental.asyncEntry` turns into a dynamic import, what they import + * statically, and their CSS. Also any stylesheet no chunk references, such as + * the one Vite combines all CSS into when `build.cssCodeSplit` is off, which + * Nuxt links on every page. + */ +function initialFiles(files: Map): Set { + const initial = new Set() + const referenced = new Set([ + ...files.values(), + ].flatMap(file => [ + ...file.css, + ...file.assets, + ])) + for (const file of files.values()) { + if (file.kind === 'css' && !referenced.has(file.fileName)) { + initial.add(file.fileName) + } + } + const visit = (fileName: string) => { + const file = files.get(fileName) + if (!file || initial.has(fileName)) { + return + } + initial.add(fileName) + for (const next of [ + ...file.imports, + ...file.css, + ]) { + visit(next) + } + } + for (const file of files.values()) { + if (file.isEntry || (file.source && APP_ENTRY_RE.test(file.source.replace(QUERY_RE, '')))) { + visit(file.fileName) + } + } + return initial +} + +interface PackageJson { + version?: string + dependencies?: Record +} + +function readPackageJson(dir: string): PackageJson | undefined { + try { + return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) + } + catch { + return undefined + } +} + +/** + * The packages that make up the framework, which ship whatever the app does: + * Nuxt and Vue, Nuxt's own dependencies, and any package only they import. A + * package that only the app or a Nuxt module imports stays the app's own. + */ +function frameworkPackages(list: ClientFile[], rootDir: string, readPackage: (dir: string) => PackageJson | undefined): Set { + const importedBy = new Map>() + const nuxtDependencies = new Set() + for (const file of list) { + for (const module of file.modules) { + const origin = originOf(module.id, rootDir) + if (origin.kind !== 'package') { + continue + } + if ((origin.name === 'nuxt' || origin.name === 'nuxt-nightly') && !importedBy.has(origin.name)) { + for (const name of Object.keys(readPackage(origin.dir!)?.dependencies ?? {})) { + nuxtDependencies.add(name) + } + } + let from = importedBy.get(origin.name) + if (!from) { + importedBy.set(origin.name, from = new Set()) + } + for (const importer of module.importers) { + const by = originOf(importer, rootDir) + // Nuxt's generated modules are how a Nuxt module's runtime gets in, so + // they don't make what they import part of the framework. + if (by.name !== origin.name) { + from.add(by.kind === 'package' + ? by.name + : `${by.kind}:${by.name}`) + } + } + } + } + // All of Nuxt's dependencies, bundled or not: one that only re-exports + // another leaves the bundle, but still brings in what it re-exports. + const framework = new Set([ + ...nuxtDependencies, + ...[ + ...importedBy.keys(), + ].filter(name => FRAMEWORK_RE.test(name)), + ]) + let grown = true + while (grown) { + grown = false + for (const [name, from] of importedBy) { + if (!framework.has(name) && from.size && [...from].every(by => framework.has(by))) { + framework.add(name) + grown = true + } + } + } + return framework +} + +export function summariseClientBundle(list: ClientFile[], rootDir: string, readPackage = readPackageJson): BundleSummary { + const files = new Map(list.map(file => [file.fileName, file])) + const initial = initialFiles(files) + const framework = frameworkPackages(list, rootDir, readPackage) + const groups = new Map() + const packageDirs = new Map>>() + const data = new Map() + const summary: BundleSummary = { + size: 0, + initial: { size: 0, gzip: 0 }, + groups: [], + duplicates: [], + data: [], + } + const addTo = (name: string, kind: BundleGroup['kind'], size: number) => { + let group = groups.get(name) + if (!group) { + groups.set(name, group = { name, kind, size: 0 }) + } + group.size += size + } + + for (const file of list) { + summary.size += file.size + if (initial.has(file.fileName)) { + summary.initial.size += file.size + summary.initial.gzip += file.gzip + } + if (file.kind === 'css') { + addTo(CSS_GROUP, 'css', file.size) + continue + } + for (const module of file.modules) { + const origin = originOf(module.id, rootDir) + if (origin.kind === 'virtual' || (origin.kind === 'package' && framework.has(origin.name))) { + addTo(FRAMEWORK_GROUP, 'framework', module.size) + } + else { + addTo(origin.kind === 'app' + ? APP_GROUP + : origin.name, origin.kind, module.size) + } + // Only app files: a package's modules are named after the package. + if (DATA_RE.test(origin.name)) { + const entry = data.get(origin.name) ?? { file: origin.name, size: 0, importedBy: [] } + entry.size += module.size + for (const importer of module.importers) { + const from = originOf(importer, rootDir).name + if (!entry.importedBy.includes(from)) { + entry.importedBy.push(from) + } + } + data.set(origin.name, entry) + } + if (origin.dir) { + let dirs = packageDirs.get(origin.name) + if (!dirs) { + packageDirs.set(origin.name, dirs = new Map()) + } + let importedBy = dirs.get(origin.dir) + if (!importedBy) { + dirs.set(origin.dir, importedBy = new Set()) + } + for (const importer of module.importers) { + const from = originOf(importer, rootDir).name + if (from !== origin.name) { + importedBy.add(from) + } + } + } + } + } + + summary.groups = [ + ...groups.values(), + ].filter(group => group.size > 0).sort((a, b) => b.size - a.size) + summary.data = [ + ...data.values(), + ].filter(entry => entry.size >= LARGE_DATA).sort((a, b) => b.size - a.size) + for (const [name, dirs] of packageDirs) { + if (dirs.size > 1) { + summary.duplicates.push({ + name, + copies: [...dirs].map(([dir, importedBy]) => ({ + version: readPackage(dir)?.version, + importedBy: [...importedBy], + })), + }) + } + } + return summary +} + +/** Whole bytes: module sizes are a share of their chunk, so rarely a whole number. */ +const formatSize = (bytes: number) => formatBytes(Math.round(bytes)) + +/** Segments of the bar with a name of their own; the rest share one. */ +const BAR_GROUPS = 4 +const BAR_MAX_WIDTH = 60 +const BAR_COLORS = ['cyan', 'green', 'yellow', 'magenta'] as const +/** Without colours, each segment needs its own character to be told apart. */ +const BAR_GLYPHS = ['█', '▓', '▒', '▪'] +const REST_GLYPH = '░' + +function listNames(names: string[]): string { + const shown = names.slice(0, 2).join(', ') + return names.length > 2 + ? `${shown} +${names.length - 2}` + : shown +} + +/** The range a caret dependency on `version` accepts: copies in the same one can be merged. */ +function compatibleRange(version: string): string { + const [major, minor] = version.split('.') + return major === '0' + ? `0.${minor}` + : major! +} + +function compareVersions(a: string, b: string): number { + const left = a.split(/[.-]/).map(Number) + const right = b.split(/[.-]/).map(Number) + for (let index = 0; index < 3; index++) { + const difference = (left[index] || 0) - (right[index] || 0) + if (difference) { + return difference + } + } + return 0 +} + +function hints(summary: BundleSummary, dedupeCommand?: string): string[] { + const hints: string[] = [] + if (summary.initial.gzip > INITIAL_BUDGET) { + hints.push(`Every page loads ${formatSize(summary.initial.gzip)} gzip, over the ${INITIAL_BUDGET / 1000} kB budget. Lazy load the pages, components and packages the first render doesn't need.`) + } + for (const entry of summary.data) { + const by = entry.importedBy.length + ? `${listNames(entry.importedBy)} bundles` + : 'The bundle includes' + hints.push(`${by} ${styleText('cyan', entry.file)} (${formatSize(entry.size)}). Fetch it at runtime instead of importing it.`) + } + for (const { name, copies } of summary.duplicates) { + const versions = copies.map(copy => [copy.version ?? 'unknown version', copy.importedBy.length && styleText('dim', `via ${listNames(copy.importedBy)}`)].filter(Boolean).join(' ')) + const known = copies.every(copy => copy.version) + const ranges = new Set(copies.map(copy => copy.version && compatibleRange(copy.version))) + const [oldest, ...newer] = [...copies].sort((a, b) => compareVersions(a.version!, b.version!)) + const fix = known && ranges.size === 1 && dedupeCommand + ? `Run ${styleText('cyan', dedupeCommand)} to merge them.` + : known && ranges.size > 1 && oldest!.importedBy.length + ? `The major versions differ: update ${listNames(oldest!.importedBy)} to a version that uses ${name} ${compatibleRange(newer.at(-1)!.version!)}.` + : 'Deduplicate it in your lockfile.' + hints.push(`${styleText('cyan', name)} is bundled ${copies.length} times: ${versions.join(', ')}. ${fix}`) + } + return hints +} + +/** Items joined by `separator`, starting a new line rather than splitting an item. */ +function joinWrapped(items: string[], separator: string, columns: number): string[] { + const lines: string[] = [] + for (const item of items) { + const last = lines.at(-1) + if (last !== undefined && visibleWidth(last + separator + item) <= columns) { + lines[lines.length - 1] = last + separator + item + } + else { + lines.push(item) + } + } + return lines +} + +/** The whole bundle as one bar, its largest parts in their own colour, and a legend under it. */ +function bundleBar(summary: BundleSummary, columns: number): string[] { + if (!summary.size) { + return [] + } + const width = Math.max(10, Math.min(BAR_MAX_WIDTH, columns)) + const colors = styleText('red', ' ') !== ' ' + const named = summary.groups.slice(0, BAR_GROUPS) + const restCount = summary.groups.length - named.length + const rest = `${restCount} other${restCount === 1 + ? '' + : 's'}` + const parts = [ + ...named.map(group => ({ name: group.name, size: group.size })), + ...(restCount + ? [ + { name: rest, size: summary.size - named.reduce((sum, group) => sum + group.size, 0) }, + ] + : []), + ] + // Every part gets at least one cell, and the cells left over go to the + // parts that lost most to rounding, so the bar is always `width` wide. + const exact = parts.map(part => part.size / summary.size * width) + const cells = exact.map(cell => Math.max(1, Math.floor(cell))) + // A part rounded up to its one cell is already past its share, so it comes last. + const order = parts.map((part, index) => index).sort((a, b) => (exact[b]! - cells[b]!) - (exact[a]! - cells[a]!)) + let spare = width - cells.reduce((sum, count) => sum + count, 0) + for (let index = 0; spare > 0; spare--, index++) { + cells[order[index % order.length]!]!++ + } + // Small parts rounded up to a cell can overfill the bar: the largest gives them room. + for (; spare < 0; spare++) { + cells[cells.indexOf(Math.max(...cells))]!-- + } + const glyph = (index: number) => { + if (index >= named.length) { + return styleText('dim', REST_GLYPH) + } + return colors + ? styleText(BAR_COLORS[index]!, '█') + : BAR_GLYPHS[index]! + } + const bar = parts.map((part, index) => glyph(index).repeat(cells[index]!)).join('') + const share = (size: number) => { + const percent = size / summary.size * 100 + return percent < 1 + ? '<1%' + : percent > 99 && percent < 100 + ? '>99%' + : `${Math.round(percent)}%` + } + const legend = parts.map((part, index) => `${glyph(index)} ${part.name} ${styleText('dim', share(part.size))}`) + return [ + bar, + ...joinWrapped(legend, ' ', columns), + ] +} + +/** + * The summary printed at the end of `nuxt build`, wrapped to `columns`. + * `projectDir` is the project relative to the current directory, which the + * analyzer command names when it is not the current one. `dedupeCommand` is + * the package manager's command to merge duplicated packages, if it has one. + */ +export function formatClientBundle(summary: BundleSummary, { columns = 80, projectDir = '', dedupeCommand }: { columns?: number, projectDir?: string, dedupeCommand?: string } = {}): string { + // No bundle total: the build report's `Client` line gives it, counting every file the build writes. + const facts = [ + ...(summary.routes === undefined + ? [] + : [`${summary.routes} route${summary.routes === 1 + ? '' + : 's'}`]), + `${styleText('dim', 'every page loads')} ${formatSize(summary.initial.gzip)} ${styleText('dim', 'gzip')}`, + ] + const lines = [ + ...joinWrapped([ + `${styleText('bold', 'Bundle (client)')} ${facts[0]}`, + ...facts.slice(1), + ], styleText('dim', ' · '), columns), + ...bundleBar(summary, columns), + ] + + // Hints wrap rather than truncate: each is a sentence to act on, so its + // continuation rows hang under its text rather than under the marker. + const found = hints(summary, dedupeCommand).flatMap(hint => wrapText(hint, columns - 2).map((row, index) => `${index + ? ' ' + : styleText('yellow', '!')} ${row}`)) + const analyze = `npx nuxt analyze${projectDir + ? ` ${/\s/.test(projectDir) + ? JSON.stringify(projectDir) + : projectDir}` + : ''}` + const footer = styleText('dim', `See what each chunk imports with ${styleText('cyan', analyze)}`) + // A command split across lines can't be copied, so it gets a line of its own instead. + const footerLines = visibleWidth(footer) <= columns + ? [footer] + : [ + styleText('dim', 'See what each chunk imports with'), + styleText('cyan', analyze), + ] + return [ + ...lines, + ...(found.length + ? ['', ...found] + : []), + '', + ...footerLines, + ].join('\n') +} + +/** The command that merges duplicated packages, for package managers that have one. */ +export async function dedupeCommandFor(rootDir: string): Promise { + const agent = (await detectPackageManager(rootDir))?.agent + return agent === 'npm' || agent === 'pnpm' + ? `${agent} dedupe` + : agent === 'yarn@berry' + ? 'yarn dedupe' + : undefined +} + +/** The page routes the app ends up with, nested ones included, each path once. */ +export function countRoutes(pages: Array<{ path: string, children?: unknown[] }>): number { + const paths = new Set() + const visit = (list: typeof pages, prefix: string) => { + for (const page of list) { + const path = page.path.startsWith('/') + ? page.path + : `${prefix}/${page.path}` + paths.add(path.replace(/\/+/g, '/').replace(/(.)\/$/, '$1')) + visit((page.children ?? []) as typeof pages, path) + } + } + visit(pages, '') + return paths.size +} + +/** + * Collect the client build while Vite writes it, so `nuxt build` can end with + * what it shipped. Returns undefined until the client is built, and always + * with a builder other than Vite. + */ +export function collectClientBundle(nuxt: Nuxt): () => BundleSummary | undefined { + let files: ClientFile[] | undefined + let routes: number | undefined + nuxt.hook('pages:resolved', (pages) => { + routes = countRoutes(pages) + }) + nuxt.hook('vite:extendConfig', (config, { isClient }) => { + if (!isClient) { + return + } + config.plugins?.push({ + name: 'nuxi:client-bundle-summary', + applyToEnvironment: environment => environment.name === 'client', + generateBundle: { + // After Vite's CSS plugin, which emits the combined stylesheet of a + // build without CSS code splitting in this same hook. + order: 'post', + handler(_options, bundle) { + const importersOf = (id: string) => { + const info = this.getModuleInfo(id) + return info + ? [ + ...info.importers, + ...info.dynamicImporters, + ] + : [] + } + files = readClientBundle( + bundle as unknown as Record, + id => outsideImporters(id, nuxt.options.rootDir, importersOf), + ) + }, + }, + }) + }) + return () => files && { + ...summariseClientBundle(files, nuxt.options.rootDir), + routes, + } +} diff --git a/packages/nuxt-cli/src/utils/logger.ts b/packages/nuxt-cli/src/utils/logger.ts index 6e47f62b7..694ba899a 100644 --- a/packages/nuxt-cli/src/utils/logger.ts +++ b/packages/nuxt-cli/src/utils/logger.ts @@ -4,7 +4,7 @@ import { intro as clackIntro, outro as clackOutro, log, S_ERROR, S_INFO, S_STEP_ import { createDebug } from 'obug' import { isCI } from 'std-env' -import { blankLineBefore, writeDirect } from './stdout' +import { blankLineBefore, trackOutputSpacing, writeDirect } from './stdout' type LoggerImpl = Pick @@ -77,6 +77,22 @@ export const logger: LoggerImpl = { message: (message, options) => emit(() => (impl ?? defaultImpl()).message(message, options)), } +/** + * Log a block of lines, such as a summary table, one blank line away from the + * output before and after it. In a terminal clack already puts its `│` spacer + * before every message, so a newline added here would double the gap. + */ +export function logBlock(block: string): void { + if (impl || (process.stdout.isTTY && !isCI)) { + logger.message(block) + return + } + // From here on the gap is measured, so a block straight after another one + // does not add a second blank line to the one the first left behind. + trackOutputSpacing() + emit(() => writeDirect(`${blankLineBefore()}${block}\n\n`)) +} + /** * Open a command's output. Falls back to a bare headline where clack's opening * corner would only introduce a gutter nothing draws against. diff --git a/packages/nuxt-cli/test/unit/client-bundle.spec.ts b/packages/nuxt-cli/test/unit/client-bundle.spec.ts new file mode 100644 index 000000000..b756cb0ed --- /dev/null +++ b/packages/nuxt-cli/test/unit/client-bundle.spec.ts @@ -0,0 +1,498 @@ +import type { BundleSummary, ClientFile } from '../../src/utils/client-bundle' + +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { countRoutes, formatClientBundle, outsideImporters, readClientBundle, summariseClientBundle } from '../../src/utils/client-bundle' +import { stripAnsi } from '../../src/utils/formatting' + +const root = '/app' +const pnpm = (name: string, version: string, file = 'dist/index.js') => `/app/node_modules/.pnpm/${name.replace('/', '+')}@${version}/node_modules/${name}/${file}` + +function js(fileName: string, options: Partial & { modules?: ClientFile['modules'] }): ClientFile { + const size = options.size ?? options.modules?.reduce((sum, module) => sum + module.size, 0) ?? 0 + return { + kind: 'js', + gzip: Math.round(size / 3), + isEntry: false, + isDynamicEntry: false, + imports: [], + css: [], + assets: [], + modules: [], + size, + fileName, + ...options, + } +} + +function css(fileName: string, size: number): ClientFile { + return { + fileName, + kind: 'css', + size, + gzip: size / 4, + isEntry: false, + isDynamicEntry: false, + imports: [], + css: [], + assets: [], + modules: [], + } +} + +describe('client bundle summary', () => { + const files = [ + js('_nuxt/entry.js', { + isEntry: true, + imports: ['_nuxt/vendor.js'], + css: ['_nuxt/entry.css'], + modules: [ + { id: '/app/app/app.vue?vue&type=script&setup=true&lang.ts', size: 2_000, importers: [] }, + { + id: pnpm('chart.js', '4.0.0'), + size: 60_000, + importers: ['/app/app/app.vue?vue&type=script&setup=true&lang.ts'], + }, + { + id: pnpm('semver', '7.0.0'), + size: 10_000, + importers: ['/app/app/app.vue'], + }, + { id: '\0vite/preload-helper.js', size: 500, importers: [] }, + ], + }), + js('_nuxt/vendor.js', { + modules: [ + // Vue's parts: part of the framework row, and three packages, not three copies of one. + { + id: pnpm('@vue/runtime-core', '3.5.0', 'dist/runtime-core.esm-bundler.js'), + size: 50_000, + importers: [ + pnpm('vue', '3.5.0', 'dist/vue.runtime.esm-bundler.js'), + ], + }, + { + id: pnpm('@vue/shared', '3.5.0', 'dist/shared.esm-bundler.js'), + size: 15_000, + importers: [ + pnpm('@vue/runtime-core', '3.5.0', 'dist/runtime-core.esm-bundler.js'), + ], + }, + { + id: pnpm('vue', '3.5.0', 'dist/vue.runtime.esm-bundler.js'), + size: 5_000, + importers: ['/app/app/app.vue?vue&type=script&setup=true&lang.ts'], + }, + ], + }), + js('_nuxt/editor.js', { + isDynamicEntry: true, + source: '/app/app/components/Editor.vue', + imports: ['_nuxt/entry.js'], + css: ['_nuxt/editor.css'], + modules: [ + { id: '/app/app/components/Editor.vue', size: 1_000, importers: [] }, + { + id: pnpm('monaco-editor', '0.50.0'), + size: 200_000, + importers: ['/app/app/components/Editor.vue'], + }, + // A dependency's own copy, nested under the package that needs it. + { + id: `${pnpm('legacy', '1.0.0').replace('/dist/index.js', '')}/node_modules/semver/index.js`, + size: 8_000, + importers: [ + pnpm('legacy', '1.0.0'), + ], + }, + ], + }), + css('_nuxt/entry.css', 3_000), + css('_nuxt/editor.css', 1_000), + ] + const versions: Record = { + [pnpm('semver', '7.0.0').replace('/dist/index.js', '')]: '7.0.0', + [`${pnpm('legacy', '1.0.0').replace('/dist/index.js', '')}/node_modules/semver`]: '6.3.1', + } + const summary = summariseClientBundle(files, root, dir => ({ version: versions[dir] })) + + it('counts what every page loads: the entry, its static imports and their CSS, not lazy chunks', () => { + expect(summary.initial.size).toBe(72_500 + 70_000 + 3_000) + expect(summary.size).toBe(72_500 + 70_000 + 209_000 + 4_000) + }) + + it('counts a stylesheet no chunk imports, as with `cssCodeSplit: false`, as loaded by every page', () => { + const combined = summariseClientBundle([ + js('_nuxt/entry.js', { isEntry: true, size: 10_000 }), + js('_nuxt/page.js', { isDynamicEntry: true, size: 2_000 }), + css('_nuxt/style.css', 5_000), + ], root) + expect(combined.initial.size).toBe(10_000 + 5_000) + }) + + it('leaves out a stylesheet a chunk only references by URL, as with `?url`', () => { + const deferred = summariseClientBundle([ + js('_nuxt/entry.js', { + isEntry: true, + size: 10_000, + assets: ['_nuxt/theme.css'], + }), + css('_nuxt/theme.css', 5_000), + ], root) + expect(deferred.initial.size).toBe(10_000) + }) + + it('counts Nuxt\'s app entry as loaded by every page when `experimental.asyncEntry` makes it a dynamic import', () => { + const asyncEntry = summariseClientBundle([ + js('_nuxt/wrapper.js', { isEntry: true, size: 1_000 }), + js('_nuxt/app.js', { + isDynamicEntry: true, + source: pnpm('nuxt', '4.7.0', 'dist/app/entry.js'), + imports: ['_nuxt/vendor.js'], + size: 100_000, + }), + js('_nuxt/vendor.js', { size: 50_000 }), + js('_nuxt/page.js', { isDynamicEntry: true, source: '/app/app/pages/index.vue', size: 2_000 }), + ], root) + expect(asyncEntry.initial.size).toBe(1_000 + 100_000 + 50_000) + }) + + it('groups Nuxt, Vue, Nuxt\'s dependencies and what only they import, but not what only the app or a Nuxt module imports', () => { + const nuxtDir = pnpm('nuxt', '4.7.0', '').replace(/\/$/, '') + const nuxtRuntime = `${nuxtDir}/dist/app/nuxt.js` + const nitroServer = pnpm('@nuxt/nitro-server', '4.7.0', 'dist/h3.mjs') + const grouped = summariseClientBundle([ + js('_nuxt/entry.js', { + isEntry: true, + modules: [ + { id: nuxtRuntime, size: 40_000, importers: [] }, + // Nuxt dependencies: the framework, even when the app imports one too. + { + id: pnpm('ufo', '1.0.0'), + size: 3_000, + importers: [nuxtRuntime, '/app/app/app.vue'], + }, + // Not a Nuxt dependency, but only a Nuxt dependency imports it: the + // framework, even though that dependency only re-exports it and so + // isn't in the bundle itself. + { + id: pnpm('h3', '1.0.0'), + size: 1_500, + importers: [nitroServer], + }, + // Only Nuxt's generated plugin list imports it, as for a Nuxt module's runtime: the app's own. + { + id: pnpm('pinia', '3.0.0'), + size: 6_000, + importers: ['/app/.nuxt/plugins.client.mjs'], + }, + // The app and a framework package import it: the app's own. + { + id: pnpm('lodash', '4.0.0'), + size: 5_000, + importers: [ + pnpm('h3', '1.0.0'), + '/app/app/app.vue', + ], + }, + { id: '/app/.nuxt/plugins.client.mjs', size: 1_000, importers: [] }, + { id: '/app/app/app.vue', size: 1_000, importers: [] }, + ], + }), + ], root, dir => dir === nuxtDir + ? { + dependencies: { 'ufo': '^1.0.0', '@nuxt/nitro-server': '4.7.0' }, + } + : undefined) + expect(grouped.groups.map(group => [group.name, group.size])).toEqual([ + ['Nuxt & Vue', 40_000 + 3_000 + 1_500 + 1_000], + ['pinia', 6_000], + ['lodash', 5_000], + ['your app', 1_000], + ]) + }) + + it('attributes modules to packages, the app, virtual modules and CSS', () => { + const groups = Object.fromEntries(summary.groups.map(group => [group.name, group])) + expect(Object.keys(groups)).toEqual([ + 'monaco-editor', + 'Nuxt & Vue', + 'chart.js', + 'semver', + 'CSS', + 'your app', + ]) + expect(groups.CSS).toMatchObject({ kind: 'css', size: 4_000 }) + expect(groups.semver).toMatchObject({ size: 18_000 }) + expect(groups['your app']).toMatchObject({ kind: 'app', size: 3_000 }) + // Vue's three packages and the virtual preload helper. + expect(groups['Nuxt & Vue']).toMatchObject({ + kind: 'framework', + size: 70_500, + }) + }) + + it('reports each copy of a duplicated package with what imports it', () => { + expect(summary.duplicates).toEqual([ + { + name: 'semver', + copies: [ + { + version: '7.0.0', + importedBy: ['app/app.vue'], + }, + { + version: '6.3.1', + importedBy: ['legacy'], + }, + ], + }, + ]) + }) + + const hintsOf = (bundle: BundleSummary, dedupeCommand?: string) => stripAnsi(formatClientBundle(bundle, { columns: 400, dedupeCommand })).split('\n').filter(line => line.startsWith('! ')) + + it('starts with the routes and what every page loads, leaving the bundle total to the build report', () => { + const first = (routes?: number) => stripAnsi(formatClientBundle({ ...summary, routes }, { columns: 200 })).split('\n')[0] + expect(first(3)).toBe('Bundle (client) 3 routes · every page loads 48.25 kB gzip') + expect(first(1)).toBe('Bundle (client) 1 route · every page loads 48.25 kB gzip') + expect(first()).toBe('Bundle (client) every page loads 48.25 kB gzip') + }) + + // The bar looks different with colours and without, so each test picks one. + const colours = (on: boolean) => { + vi.stubEnv('NO_COLOR', on + ? '' + : '1') + vi.stubEnv('FORCE_COLOR', on + ? '1' + : '0') + } + afterEach(() => { + vi.unstubAllEnvs() + }) + + it('shows the bundle as one bar, its four largest parts named and the rest together', () => { + colours(false) + const [, bar, legend] = formatClientBundle(summary, { columns: 200 }).split('\n') + // 355.5 kB over 60 cells: monaco-editor 33.8, Nuxt & Vue 11.9, chart.js 10.1, semver 3.0, CSS and the app 1.2. + expect(bar).toBe(`${'█'.repeat(34)}${'▓'.repeat(12)}${'▒'.repeat(10)}${'▪'.repeat(3)}░`) + expect(legend).toBe('█ monaco-editor 56% ▓ Nuxt & Vue 20% ▒ chart.js 17% ▪ semver 5% ░ 2 others 2%') + }) + + it('tells the parts of the bar apart by colour when the terminal has colours', () => { + colours(true) + const [, bar] = formatClientBundle(summary, { columns: 200 }).split('\n') + expect(stripAnsi(bar!)).toBe(`${'█'.repeat(59)}░`) + for (const code of [36, 32, 33, 35]) { + expect(bar).toContain(`\u001B[${code}m█`) + } + }) + + it('keeps the bar its width when small parts each need a cell of their own', () => { + colours(false) + const skewed = summariseClientBundle([ + js('_nuxt/entry.js', { + isEntry: true, + modules: [ + { + id: pnpm('big', '1.0.0'), + size: 1_000_000, + importers: [], + }, + ...['a', 'b', 'c', 'd'].map(name => ({ + id: pnpm(name, '1.0.0'), + size: 1_000, + importers: [], + })), + ], + }), + ], root) + const [, bar, legend] = formatClientBundle(skewed, { columns: 200 }).split('\n') + expect(bar).toBe(`${'█'.repeat(56)}▓▒▪░`) + expect(legend).toBe('█ big >99% ▓ a <1% ▒ b <1% ▪ c <1% ░ 1 other <1%') + }) + + it('names what to update when the copies of a duplicated package differ in major version', () => { + expect(hintsOf(summary, 'pnpm dedupe')).toEqual([ + '! semver is bundled 2 times: 7.0.0 via app/app.vue, 6.3.1 via legacy. The major versions differ: update legacy to a version that uses semver 7.', + ]) + }) + + it('suggests the package manager\'s dedupe command for copies one version range can share', () => { + const copies = (older: string, newer: string): BundleSummary => ({ + ...summary, + duplicates: [ + { + name: 'semver', + copies: [ + { + version: newer, + importedBy: ['app/app.vue'], + }, + { + version: older, + importedBy: ['legacy'], + }, + ], + }, + ], + }) + expect(hintsOf(copies('7.5.0', '7.6.3'), 'pnpm dedupe')).toEqual([ + '! semver is bundled 2 times: 7.6.3 via app/app.vue, 7.5.0 via legacy. Run pnpm dedupe to merge them.', + ]) + expect(hintsOf(copies('7.5.0', '7.6.3'))).toEqual([ + '! semver is bundled 2 times: 7.6.3 via app/app.vue, 7.5.0 via legacy. Deduplicate it in your lockfile.', + ]) + // Below 1.0.0, a minor version is as breaking as a major one. + expect(hintsOf(copies('0.5.1', '0.6.0'), 'pnpm dedupe')).toEqual([ + '! semver is bundled 2 times: 0.6.0 via app/app.vue, 0.5.1 via legacy. The major versions differ: update legacy to a version that uses semver 0.6.', + ]) + }) + + it('hints when every page loads more than 200 kB gzip', () => { + // The fixture's JavaScript gzips to a third of its size. + const entry = (size: number) => summariseClientBundle([ + js('_nuxt/entry.js', { isEntry: true, size }), + ], root) + expect(hintsOf(entry(600_000))).toEqual([]) + expect(hintsOf(entry(630_000))).toEqual([ + '! Every page loads 210.00 kB gzip, over the 200 kB budget. Lazy load the pages, components and packages the first render doesn\'t need.', + ]) + }) + + it('hints at a data file of 100 kB or more the app bundles, but not a smaller one or one inside a package', () => { + const page = '/app/app/pages/evals.vue?vue&type=script&setup=true&lang.ts' + const withData = summariseClientBundle([ + js('_nuxt/evals.js', { + isDynamicEntry: true, + source: page, + modules: [ + { id: page, size: 1_000, importers: [] }, + { + id: '/app/app/data/results.json', + size: 100_000, + importers: [page], + }, + { + id: '/app/app/data/labels.json', + size: 99_999, + importers: [page], + }, + { + id: pnpm('emojibase-data', '1.0.0', 'en/data.json'), + size: 300_000, + importers: [page], + }, + ], + }), + ], root) + expect(hintsOf(withData)).toEqual([ + '! app/pages/evals.vue bundles app/data/results.json (100.00 kB). Fetch it at runtime instead of importing it.', + ]) + }) + + it('points the analyzer at the project when it is not the current directory', () => { + const footer = (projectDir?: string) => stripAnsi(formatClientBundle(summary, { columns: 200, projectDir })).split('\n').at(-1) + expect(footer()).toBe('See what each chunk imports with npx nuxt analyze') + expect(footer('playground')).toBe('See what each chunk imports with npx nuxt analyze playground') + expect(footer('my app')).toBe('See what each chunk imports with npx nuxt analyze "my app"') + }) + + it('puts the analyzer command on a line of its own rather than splitting it when the footer is too wide', () => { + const lines = stripAnsi(formatClientBundle(summary, { columns: 50, projectDir: 'playground' })).split('\n') + expect(lines.slice(-2)).toEqual([ + 'See what each chunk imports with', + 'npx nuxt analyze playground', + ]) + }) + + it('fits every line to the terminal width, wrapping between facts and legend items and hints under their text', () => { + colours(false) + const lines = formatClientBundle({ ...summary, routes: 12 }, { columns: 40 }).split('\n') + expect(Math.max(...lines.map(line => line.length))).toBeLessThanOrEqual(40) + expect(lines.slice(0, 6)).toEqual([ + 'Bundle (client) 12 routes', + 'every page loads 48.25 kB gzip', + `${'█'.repeat(22)}${'▓'.repeat(8)}${'▒'.repeat(7)}${'▪'.repeat(2)}░`, + '█ monaco-editor 56% ▓ Nuxt & Vue 20%', + '▒ chart.js 17% ▪ semver 5%', + '░ 2 others 2%', + ]) + const hint = lines.findIndex(line => line.startsWith('! semver')) + expect(lines.slice(hint, hint + 2)).toEqual([ + '! semver is bundled 2 times: 7.0.0 via', + ' app/app.vue, 6.3.1 via legacy. The', + ]) + }) +}) + +describe('counting routes', () => { + it('counts nested routes once each, an index child as its parent\'s route', () => { + expect(countRoutes([ + { path: '/' }, + { + path: '/admin', + children: [ + { path: '' }, + { path: 'users' }, + { path: 'users/:id' }, + ], + }, + { path: '/about' }, + ])).toBe(5) + }) +}) + +describe('reading the bundle', () => { + it('spreads a chunk\'s final size over its modules by their share before minification', () => { + const [file] = readClientBundle({ + 'a.js': { + type: 'chunk', + fileName: 'a.js', + code: 'x'.repeat(100), + isEntry: true, + isDynamicEntry: false, + facadeModuleId: null, + imports: [], + modules: { + a: { renderedLength: 300 }, + b: { renderedLength: 100 }, + c: { renderedLength: 0 }, + }, + }, + }) + expect(file!.modules.map(module => [module.id, module.size])).toEqual([ + ['a', 75], + ['b', 25], + ['c', 0], + ]) + }) + + it('finds what imports a package from outside it, through re-exports and cycles in its own files', () => { + const graph: Record = { + // `index.js` only re-exports `inner.js`, and `a.js` and `b.js` import each other. + [pnpm('yaml', '2.9.1', 'dist/inner.js')]: [ + pnpm('yaml', '2.9.1', 'dist/index.js'), + pnpm('yaml', '2.9.1', 'dist/a.js'), + ], + [pnpm('yaml', '2.9.1', 'dist/index.js')]: ['/app/app/app.vue'], + [pnpm('yaml', '2.9.1', 'dist/a.js')]: [ + pnpm('yaml', '2.9.1', 'dist/b.js'), + ], + [pnpm('yaml', '2.9.1', 'dist/b.js')]: [ + pnpm('yaml', '2.9.1', 'dist/a.js'), + pnpm('legacy', '1.0.0'), + ], + // An app file has no package to look through: its direct importers stand. + '/app/app/utils.ts': ['/app/app/helper.ts'], + '/app/app/helper.ts': ['/app/app/app.vue'], + } + const importersOf = (id: string) => graph[id] ?? [] + expect(outsideImporters(pnpm('yaml', '2.9.1', 'dist/inner.js'), root, importersOf).sort()).toEqual([ + pnpm('legacy', '1.0.0'), + '/app/app/app.vue', + ].sort()) + expect(outsideImporters('/app/app/utils.ts', root, importersOf)).toEqual(['/app/app/helper.ts']) + }) +}) diff --git a/packages/nuxt-cli/test/unit/commands/build.spec.ts b/packages/nuxt-cli/test/unit/commands/build.spec.ts index 13e42e27a..e92e3d6c2 100644 --- a/packages/nuxt-cli/test/unit/commands/build.spec.ts +++ b/packages/nuxt-cli/test/unit/commands/build.spec.ts @@ -58,6 +58,7 @@ vi.mock('../../../src/utils/logger', () => ({ message: vi.fn(), success: vi.fn(), }, + logBlock: vi.fn(), intro: vi.fn(), outro: vi.fn(), })) diff --git a/packages/nuxt-cli/test/unit/utils/logger.spec.ts b/packages/nuxt-cli/test/unit/utils/logger.spec.ts index 5d15588b6..da16568d3 100644 --- a/packages/nuxt-cli/test/unit/utils/logger.spec.ts +++ b/packages/nuxt-cli/test/unit/utils/logger.spec.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { stripAnsi } from '../../../src/utils/formatting' -import { logger } from '../../../src/utils/logger' +import { logBlock, logger } from '../../../src/utils/logger' const environment = vi.hoisted(() => ({ isCI: false })) @@ -71,4 +71,27 @@ describe('logger', () => { expect(written()).toBe('● Ready in 2.4s\n config 320ms\n') }) + + // Last in the file: the first block outside a terminal starts watching stdout for good. + it('should keep summary blocks one blank line apart in a terminal', () => { + const { written } = capture(true) + + logBlock('Bundle (client)\n_nuxt/entry.js') + logBlock('Route rules\n/ prerender') + logger.success('Server built') + + expect(written()).not.toMatch(/│\n│\n/) + expect(written()).toMatch(/│ {2}_nuxt\/entry\.js\n│\n│ {2}Route rules\n.*\n│\n◆ {2}Server built\n$/) + }) + + it('should keep summary blocks one blank line apart in redirected output', () => { + const { written } = capture(false) + + logger.info('Bundling app') + logBlock('Bundle (client)\n_nuxt/entry.js') + logBlock('Route rules\n/ prerender') + logger.success('Server built') + + expect(written()).toBe('● Bundling app\n\nBundle (client)\n_nuxt/entry.js\n\nRoute rules\n/ prerender\n\n◆ Server built\n') + }) })