From 8e573aac284349f5ef795da5c06d430b94cdaaaa Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Thu, 19 Nov 2026 17:11:23 +0900 Subject: [PATCH] perf(next-plugin): share what the root layout imports across every route A production webpack build counted Next's root layout (or template, or pages/_app) as a route of its own, so what only it imports kept a per-file stylesheet that every page loaded anyway. A shell that wraps every route of its router now counts with those routes when atoms are hoisted, so its imports join the shared devup-ui.css with short names. A nested layout stays a route of its own; lazily loaded files and other entries keep theirs. Dev, Turbopack and plain webpack/Rsbuild builds are unchanged. The one-route Turbopack test reads the layout from the coordinator options, as in #1033, since #1036 removed singleCss from the loader options. Co-Authored-By: Claude Opus 5.5 --- ...hangepack_log_route_shells_shared_css.json | 9 + .../next-plugin/src/__tests__/plugin.test.ts | 22 +- packages/next-plugin/src/plugin.ts | 7 + .../src/__tests__/route-shells.test.ts | 198 ++++++++++++++++++ packages/plugin-utils/src/index.ts | 1 + packages/plugin-utils/src/route-shells.ts | 97 +++++++++ .../src/__tests__/plugin.test.ts | 62 ++++++ .../src/__tests__/route-shells-build.cjs | 102 +++++++++ .../src/__tests__/route-shells-build.test.ts | 76 +++++++ packages/webpack-plugin/src/plugin.ts | 17 +- 10 files changed, 576 insertions(+), 15 deletions(-) create mode 100644 .changepacks/changepack_log_route_shells_shared_css.json create mode 100644 packages/plugin-utils/src/__tests__/route-shells.test.ts create mode 100644 packages/plugin-utils/src/route-shells.ts create mode 100644 packages/webpack-plugin/src/__tests__/route-shells-build.cjs create mode 100644 packages/webpack-plugin/src/__tests__/route-shells-build.test.ts diff --git a/.changepacks/changepack_log_route_shells_shared_css.json b/.changepacks/changepack_log_route_shells_shared_css.json new file mode 100644 index 000000000..49578ebc7 --- /dev/null +++ b/.changepacks/changepack_log_route_shells_shared_css.json @@ -0,0 +1,9 @@ +{ + "changes": { + "packages/next-plugin/package.json": "Patch", + "packages/plugin-utils/package.json": "Patch", + "packages/webpack-plugin/package.json": "Patch" + }, + "note": "A Next production webpack build of an app with several routes now counts the root `layout` or `template` (or `pages/_app`), which Next renders with every route, as part of those routes when it hoists atoms, instead of as a route of its own. What it imports (a header, a footer) then reaches every route and joins the shared `devup-ui.css` with short class names, instead of a stylesheet of its own that every page loaded anyway. A nested layout that wraps only some routes stays a route of its own, so its styles never load outside it; lazily loaded files and other entries keep their own routes. `next dev`, Turbopack and apps without a layout keep their output; plain webpack and Rsbuild builds are unchanged unless they set the new `routeShells` option.", + "date": "2026-11-19T00:00:00.000Z" +} diff --git a/packages/next-plugin/src/__tests__/plugin.test.ts b/packages/next-plugin/src/__tests__/plugin.test.ts index 349ee6761..e21c335d3 100644 --- a/packages/next-plugin/src/__tests__/plugin.test.ts +++ b/packages/next-plugin/src/__tests__/plugin.test.ts @@ -470,6 +470,7 @@ describe('DevupUINextPlugin', () => { singleCss: true, cssDir: resolve('.next/cache', 'devup-ui'), productionPrewarmFiles: [], + routeShells: true, }) }, ) @@ -517,6 +518,7 @@ describe('DevupUINextPlugin', () => { cssDir: resolve('.next/cache', 'devup-ui'), engine: 'native', productionPrewarmFiles: [], + routeShells: true, }) }) @@ -620,6 +622,7 @@ describe('DevupUINextPlugin', () => { engine: 'native', cssDir: resolve('.next/cache', 'devup-ui'), productionPrewarmFiles: [], + routeShells: true, }) }) @@ -641,6 +644,7 @@ describe('DevupUINextPlugin', () => { engine: 'native', cssDir: resolve('.next/cache', 'devup-ui'), productionPrewarmFiles: [], + routeShells: true, }) expect(webpack).toHaveBeenCalled() }) @@ -672,19 +676,11 @@ describe('DevupUINextPlugin', () => { ).mockReturnValue(true) try { // When - const config = DevupUI({}, options) as { - turbopack: { - rules: Record< - string, - { loaders: { options: { singleCss: boolean } }[] } - > - } - } - // Then the loaders extract into the layout chosen - expect( - config.turbopack.rules['*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}'] - .loaders[0].options.singleCss, - ).toBe(expected) + DevupUI({}, options) + // Then the coordinator extracts into the layout chosen + expect(startCoordinatorSpy).toHaveBeenCalledWith( + expect.objectContaining({ singleCss: expected }), + ) } finally { singleRoute.mockRestore() graphSpy.mockRestore() diff --git a/packages/next-plugin/src/plugin.ts b/packages/next-plugin/src/plugin.ts index 96b2a8d00..8c30ce804 100644 --- a/packages/next-plugin/src/plugin.ts +++ b/packages/next-plugin/src/plugin.ts @@ -62,6 +62,11 @@ export type DevupUINextPluginOptions = Partial & { * Atom-level route-aware hoisting threshold for webpack (default 2; 0 disables). * Turbopack keeps per-file names until shared class-slot reservation lands in * #752; explicit finite positive requests warn once. Ignored in singleCss mode. + * + * A production webpack build counts the root `layout` (or `pages/_app`), + * which wraps every route, with those routes rather than as a route of its + * own, so what it imports joins the shared `devup-ui.css`. A nested layout + * stays a route of its own. */ atomHoist?: number } @@ -946,6 +951,8 @@ export function DevupUI( ? undefined : productionPrewarmFiles, ...(!_options.dev && singleRoute ? { singleCss: true } : {}), + // A layout counts with the routes it wraps (production only) + ...(_options.dev ? {} : { routeShells: true }), }), ) if (typeof webpack === 'function') return webpack(config, _options) diff --git a/packages/plugin-utils/src/__tests__/route-shells.test.ts b/packages/plugin-utils/src/__tests__/route-shells.test.ts new file mode 100644 index 000000000..1f6a11e6c --- /dev/null +++ b/packages/plugin-utils/src/__tests__/route-shells.test.ts @@ -0,0 +1,198 @@ +import { join } from 'node:path' + +import { describe, expect, it } from 'bun:test' + +import { computeFileReach, type StaticImportGraph } from '../import-graph' +import { withRouteShells } from '../route-shells' + +const root = join(import.meta.dir, 'route-shells-root') +const at = (path: string) => join(root, path) + +function graphOf(edges: Record): StaticImportGraph { + const files = [ + ...new Set([...Object.keys(edges), ...Object.values(edges).flat()]), + ].map(at) + const staticImports = new Map(files.map((file) => [file, new Set()])) + const staticImporters = new Map( + files.map((file) => [file, new Set()]), + ) + for (const [from, targets] of Object.entries(edges)) + for (const target of targets) { + staticImports.get(at(from))!.add(at(target)) + staticImporters.get(at(target))!.add(at(from)) + } + return { + files, + fileSet: new Set(files), + staticImports, + staticImporters, + dynamicImports: new Map(files.map((file) => [file, new Set()])), + dynamicTargets: new Set(), + } +} + +/** How many routes reach each file, as atom hoisting counts them */ +function reachCounts(graph: StaticImportGraph, routes: string[]) { + return Object.fromEntries( + Object.entries( + computeFileReach({ + srcDir: root, + cwd: root, + keyBy: 'cwd-relative', + graph, + entries: routes, + }), + ).map(([file, reach]) => [file, reach.length]), + ) +} + +describe('withRouteShells', () => { + it('counts what a root layout imports as reached by every route it wraps', () => { + // Given: Next's entries, the layout among them + const graph = graphOf({ + 'src/app/layout.tsx': ['src/components/Header.tsx'], + 'src/app/page.tsx': [], + 'src/app/a/page.tsx': [], + 'src/app/not-found.tsx': [], + }) + const routes = [ + 'src/app/layout.tsx', + 'src/app/page.tsx', + 'src/app/a/page.tsx', + 'src/app/not-found.tsx', + ].map(at) + + // When + const reach = withRouteShells(graph, routes, root) + + // Then: the layout is no route; the three routes below it reach it + expect(reach.routes).toEqual(routes.slice(1)) + expect(reachCounts(reach.graph, reach.routes)).toMatchObject({ + 'src/app/layout.tsx': 3, + 'src/components/Header.tsx': 3, + }) + // As a route of its own, the header counted once + expect(reachCounts(graph, routes)['src/components/Header.tsx']).toBe(1) + // The input graph is left as it was + expect(graph.staticImports.get(at('src/app/page.tsx'))?.size).toBe(0) + }) + + it('keeps a nested layout or template that wraps only some routes a route of its own', () => { + const graph = graphOf({ + 'app/layout.tsx': [], + 'app/(shop)/template.tsx': ['components/Cart.tsx'], + 'app/(shop)/cart/page.tsx': [], + 'app/(shop)/checkout/loading.tsx': [], + 'app/about/page.tsx': [], + }) + const routes = [ + 'app/layout.tsx', + 'app/(shop)/template.tsx', + 'app/(shop)/cart/page.tsx', + 'app/(shop)/checkout/loading.tsx', + 'app/about/page.tsx', + ].map(at) + + const reach = withRouteShells(graph, routes, root) + + // The root layout wraps every route; the template only the shop's, so its + // styles stay off the about page + expect(reach.routes).toContain(at('app/(shop)/template.tsx')) + expect(reach.routes).not.toContain(at('app/layout.tsx')) + expect(reachCounts(reach.graph, reach.routes)).toMatchObject({ + 'app/layout.tsx': 3, + 'app/(shop)/template.tsx': 1, + 'components/Cart.tsx': 1, + }) + }) + + it('wraps every Pages Router page in _app, not the API routes or _document', () => { + const graph = graphOf({ + 'pages/_app.tsx': ['components/Nav.tsx'], + 'pages/index.tsx': [], + 'pages/blog/[slug].tsx': [], + 'pages/api/hello.ts': [], + 'pages/_document.tsx': [], + }) + const routes = [ + 'pages/_app.tsx', + 'pages/index.tsx', + 'pages/blog/[slug].tsx', + 'pages/api/hello.ts', + 'pages/_document.tsx', + ].map(at) + + const reach = withRouteShells(graph, routes, root) + + expect(reachCounts(reach.graph, reach.routes)).toMatchObject({ + 'components/Nav.tsx': 2, + 'pages/api/hello.ts': 1, + 'pages/_document.tsx': 1, + }) + }) + + it('keeps routes no shell wraps as they are', () => { + // Given: a lazily loaded component and an entry outside the app directory + const graph = graphOf({ + 'app/layout.tsx': ['components/Header.tsx'], + 'app/page.tsx': [], + 'app/Chart.tsx': [], + 'src/worker.ts': [], + }) + const routes = [ + 'app/layout.tsx', + 'app/page.tsx', + 'app/Chart.tsx', + 'src/worker.ts', + ].map(at) + + const reach = withRouteShells(graph, routes, root) + + expect(reach.graph.staticImports.get(at('app/Chart.tsx'))?.size).toBe(0) + expect(reach.graph.staticImports.get(at('src/worker.ts'))?.size).toBe(0) + expect(reachCounts(reach.graph, reach.routes)).toMatchObject({ + 'components/Header.tsx': 1, + }) + }) + + it('keeps a layout no route sits below a route of its own', () => { + const graph = graphOf({ + 'app/layout.tsx': [], + 'app/page.tsx': [], + 'app/empty/layout.tsx': ['components/Unused.tsx'], + }) + const routes = [ + 'app/layout.tsx', + 'app/page.tsx', + 'app/empty/layout.tsx', + ].map(at) + + const reach = withRouteShells(graph, routes, root) + + expect(reach.routes).toEqual([ + at('app/page.tsx'), + at('app/empty/layout.tsx'), + ]) + }) + + it('adds an edge for a route the graph lists no imports of', () => { + const graph = graphOf({ 'app/layout.tsx': [] }) + const route = at('app/page.tsx') + + const reach = withRouteShells(graph, [at('app/layout.tsx'), route], root) + + expect([...reach.graph.staticImports.get(route)!]).toEqual([ + at('app/layout.tsx'), + ]) + }) + + it('returns the graph untouched without a shell', () => { + const graph = graphOf({ 'src/a.ts': [], 'src/b.ts': [] }) + const routes = [at('src/a.ts'), at('src/b.ts')] + + const reach = withRouteShells(graph, routes, root) + + expect(reach.graph).toBe(graph) + expect(reach.routes).toEqual(routes) + }) +}) diff --git a/packages/plugin-utils/src/index.ts b/packages/plugin-utils/src/index.ts index e542401df..5e554d6eb 100644 --- a/packages/plugin-utils/src/index.ts +++ b/packages/plugin-utils/src/index.ts @@ -76,6 +76,7 @@ export { type ReservationInventory, } from './reservation-discovery' export { reservationGraph, reservationRoutes } from './reservation-graph' +export { withRouteShells } from './route-shells' export { isRuntimePackage, RUNTIME_PACKAGE } from './runtime-package' export { createNodeModulesExcludeRegex, diff --git a/packages/plugin-utils/src/route-shells.ts b/packages/plugin-utils/src/route-shells.ts new file mode 100644 index 000000000..15fca778d --- /dev/null +++ b/packages/plugin-utils/src/route-shells.ts @@ -0,0 +1,97 @@ +import { dirname, relative } from 'node:path' + +import type { StaticImportGraph } from './import-graph' + +const SOURCE = '(?:tsx|ts|mts|cts|jsx|js|mjs|cjs)' +/** An App Router file Next renders around every route below its directory */ +const APP_SHELL = new RegExp( + `(?:^|/)app/(?:.*/)?(?:layout|template)\\.${SOURCE}$`, +) +/** The App Router files Next renders inside the layouts above them */ +const APP_WRAPPED = new RegExp( + `(?:^|/)app/(?:.*/)?(?:page|default|not-found|forbidden|unauthorized|loading|error)\\.${SOURCE}$`, +) +/** The Pages Router file Next renders around every page */ +const PAGES_SHELL = new RegExp(`(?:^|/)pages/_app\\.${SOURCE}$`) +/** The Pages Router pages Next renders inside `_app` */ +const PAGES_WRAPPED = new RegExp( + `(?:^|/)pages/(?!api/|_document\\.).*\\.${SOURCE}$`, +) + +interface Shell { + readonly file: string + /** POSIX directory, relative to the root, holding the routes it wraps */ + readonly dir: string + /** The routes of its kind it wraps */ + readonly wraps: RegExp +} + +function toPosix(root: string, file: string): string { + return relative(root, file).replaceAll('\\', '/') +} + +/** `child` is `dir` itself or inside it (both POSIX, root-relative) */ +function isWithin(dir: string, child: string): boolean { + return child === dir || child.startsWith(`${dir}/`) +} + +function shellOf(root: string, file: string): Shell | undefined { + const path = toPosix(root, file) + if (APP_SHELL.test(path)) + return { file, dir: dirname(path), wraps: APP_WRAPPED } + if (PAGES_SHELL.test(path)) + return { file, dir: dirname(path), wraps: PAGES_WRAPPED } + return undefined +} + +/** + * The routes of a Next.js build as atom hoisting should count them. Next + * compiles each `layout`, `template` and `pages/_app` as an entry of its own, + * yet renders it with every route below its directory: as a route, the files + * only it imports count as reached by one route and keep a stylesheet of their + * own, which every page loads anyway. + * + * A shell that wraps every route of its router (the root layout, `_app`) is + * no route here; each of those routes reaches it instead, so what it imports + * reaches every route and is shared. A shell that wraps only some routes (a + * nested layout) stays a route of its own, so its styles never load on the + * pages outside it. Other routes (lazy-loaded files, other entries) are kept + * as they are and reach no shell, so what only they import stays per-file. + * + * Returns a graph that differs only in those added route-to-shell edges. + */ +export function withRouteShells( + graph: StaticImportGraph, + routes: readonly string[], + root: string, +): { graph: StaticImportGraph; routes: string[] } { + const shells: Shell[] = [] + const pages: string[] = [] + for (const route of routes) { + const shell = shellOf(root, route) + if (shell) shells.push(shell) + else pages.push(route) + } + const wrapped = new Map() + const kept = [...pages] + for (const shell of shells) { + const ofKind = pages.filter((page) => shell.wraps.test(toPosix(root, page))) + const below = ofKind.filter((page) => + isWithin(shell.dir, dirname(toPosix(root, page))), + ) + if (below.length === 0 || below.length < ofKind.length) { + kept.push(shell.file) + continue + } + for (const page of below) + wrapped.set(page, [...(wrapped.get(page) ?? []), shell.file]) + } + if (wrapped.size === 0) return { graph, routes: kept } + const staticImports = new Map(graph.staticImports) + for (const [page, files] of wrapped) + staticImports.set( + page, + new Set([...(graph.staticImports.get(page) ?? []), ...files]), + ) + return { graph: { ...graph, staticImports }, routes: kept } +} diff --git a/packages/webpack-plugin/src/__tests__/plugin.test.ts b/packages/webpack-plugin/src/__tests__/plugin.test.ts index 540cedf45..15c9a6f50 100644 --- a/packages/webpack-plugin/src/__tests__/plugin.test.ts +++ b/packages/webpack-plugin/src/__tests__/plugin.test.ts @@ -500,6 +500,7 @@ describe('devupUIWebpackPlugin', () => { engine: 'native', licenseBanner: true, atomHoist: 2, + routeShells: false, }) }, ) @@ -732,6 +733,7 @@ describe('devupUIWebpackPlugin', () => { engine: 'wasm', licenseBanner: true, atomHoist: 2, + routeShells: false, }) }) @@ -1356,6 +1358,66 @@ describe('devupUIWebpackPlugin', () => { } }) + it.each([true, false])( + 'counts a layout with the routes it wraps when routeShells is %s', + async (routeShells) => { + const project = fs.mkdtempSync( + join(tmpdir(), 'devup-ui-webpack-shells-'), + ) + reservationSpy.mockRestore() + readFileSyncSpy.mockRestore() + existsSyncSpy.mockImplementation((path) => realExistsSync(String(path))) + using _reserve = spyOn(wasm, 'reserveClassSlots').mockReturnValue( + undefined, + ) + try { + for (const [path, code] of [ + ['app/layout.tsx', "import '../lib/header'"], + ['app/page.tsx', 'export {}'], + ['app/a/page.tsx', 'export {}'], + ['lib/header.tsx', 'export {}'], + ]) + await Bun.write(join(project, path), code) + const compiler = createCompiler() + compiler.options.context = project + compiler.options.entry = { + layout: { import: ['./app/layout.tsx'] }, + home: { import: ['./app/page.tsx'] }, + a: { import: ['./app/a/page.tsx'] }, + } + applyAndRun( + new DevupUIWebpackPlugin({ engine: 'wasm', routeShells }), + compiler, + ) + const [{ graph, entries }] = computeFileReachSpy.mock.calls.at( + -1, + ) as [ + { + graph: { staticImports: Map> } + entries: string[] + }, + ] + const layout = join(project, 'app/layout.tsx') + // A shell is no route; each page reaches it instead + expect(entries.includes(layout)).toBe(!routeShells) + expect( + graph.staticImports + .get(join(project, 'app/a/page.tsx')) + ?.has(layout), + ).toBe(routeShells) + // Collapse still plans over the graph as discovered + const [{ graph: planned }] = buildCanonicalMapSpy.mock.calls.at( + -1, + ) as [{ graph: { staticImports: Map> } }] + expect( + planned.staticImports.get(join(project, 'app/a/page.tsx'))?.size, + ).toBe(0) + } finally { + fs.rmSync(project, { recursive: true, force: true }) + } + }, + ) + it('runs single-importer collapse when atomHoist is explicitly zero, without hoisting', () => { // Constraint: single-importer collapse must ALWAYS be on. The canonical // map is built + imported unconditionally; only atom HOISTING is gated. diff --git a/packages/webpack-plugin/src/__tests__/route-shells-build.cjs b/packages/webpack-plugin/src/__tests__/route-shells-build.cjs new file mode 100644 index 000000000..e970b70f3 --- /dev/null +++ b/packages/webpack-plugin/src/__tests__/route-shells-build.cjs @@ -0,0 +1,102 @@ +// Builds a Next-like app (a root layout entry plus page entries) with real +// webpack and prints the stylesheets the plugin writes, as JSON. +const assert = require('node:assert/strict') +const { + mkdirSync, + readdirSync, + readFileSync, + writeFileSync, +} = require('node:fs') +const { dirname, join } = require('node:path') +const { + webpack, +} = require('../../../next-plugin/node_modules/next/dist/compiled/webpack/webpack') + +console.info = (...args) => console.error(...args) + +const [fixture, shells, layout] = process.argv.slice(2) +assert(fixture && ['on', 'off'].includes(shells)) +mkdirSync(fixture, { recursive: true }) +process.chdir(fixture) + +function put(path, text) { + const absolute = join(fixture, path) + mkdirSync(dirname(absolute), { recursive: true }) + writeFileSync(absolute, text) +} + +put('devup.json', '{}') +put( + 'src/components/Header.js', + `import { css } from '@devup-ui/react'; +export const header = css({ color: 'white', fontSize: [14, null, 18], _hover: { color: 'orange' } });`, +) +put( + 'src/components/Card.js', + `import { css } from '@devup-ui/react'; +export const card = css({ padding: [12, null, 20], _hover: { boxShadow: '0 2px 8px #0003' } });`, +) +put( + 'src/app/layout.js', + `import { header } from '../components/Header.js'; +export default function Layout() { return header }`, +) +put( + 'src/app/page.js', + `import { css } from '@devup-ui/react'; import { card } from '../components/Card.js'; +export default function Home() { return [card, css({ color: 'teal' })] }`, +) +put( + 'src/app/a/page.js', + `import { css } from '@devup-ui/react'; import { card } from '../../components/Card.js'; +export default function A() { return [card, css({ color: 'white', fontSize: 20 })] }`, +) +put( + 'src/app/b/page.js', + `import { css } from '@devup-ui/react'; +export default function B() { return css({ color: 'maroon', margin: [4, null, 12], _focus: { outline: '1px solid' } }) }`, +) + +const { DevupUIWebpackPlugin } = require('../../dist/index.cjs') +const pages = [ + './src/app/page.js', + './src/app/a/page.js', + './src/app/b/page.js', +] +const compiler = webpack({ + mode: 'production', + context: fixture, + cache: false, + devtool: false, + entry: Object.fromEntries( + [...(layout === 'none' ? [] : ['./src/app/layout.js']), ...pages].map( + (entry, index) => [`e${index}`, entry], + ), + ), + output: { path: join(fixture, 'out'), filename: '[name].js', clean: true }, + optimization: { minimize: false }, + experiments: { css: true }, + module: { rules: [{ test: /\.css$/, type: 'css' }] }, + plugins: [ + new DevupUIWebpackPlugin({ + engine: 'wasm', + productionPrewarmFiles: [], + routeShells: shells === 'on', + }), + ], +}) + +compiler.run((error, stats) => { + if (error) throw error + assert(stats && !stats.hasErrors(), stats?.toString()) + const cssDir = join(fixture, 'df', 'devup-ui') + const sheets = Object.fromEntries( + readdirSync(cssDir) + .filter((name) => name.endsWith('.css')) + .sort() + .map((name) => [name, readFileSync(join(cssDir, name), 'utf-8')]), + ) + compiler.close(() => { + process.stdout.write(`${JSON.stringify(sheets)}\n`) + }) +}) diff --git a/packages/webpack-plugin/src/__tests__/route-shells-build.test.ts b/packages/webpack-plugin/src/__tests__/route-shells-build.test.ts new file mode 100644 index 000000000..a0100f403 --- /dev/null +++ b/packages/webpack-plugin/src/__tests__/route-shells-build.test.ts @@ -0,0 +1,76 @@ +import assert from 'node:assert/strict' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { expect, it } from 'bun:test' + +type Sheets = Record + +function build(shells: 'on' | 'off', layout: 'root' | 'none' = 'root'): Sheets { + const fixture = mkdtempSync(join(tmpdir(), 'devup-route-shells-')) + try { + const child = Bun.spawnSync( + [ + 'node', + join(import.meta.dir, 'route-shells-build.cjs'), + fixture, + shells, + layout, + ], + { stdout: 'pipe', stderr: 'pipe', timeout: 45000 }, + ) + assert.equal( + child.exitCode, + 0, + child.stdout.toString() + child.stderr.toString(), + ) + return JSON.parse(child.stdout.toString()) as Sheets + } finally { + rmSync(fixture, { recursive: true, force: true }) + } +} + +/** The sheet whose own rules (after the shared import) hold `needle` */ +function sheetWith(sheets: Sheets, needle: string): string | undefined { + return Object.keys(sheets).find((name) => sheets[name]!.includes(needle)) +} + +it('hoists what a layout imports into the shared sheet, in cascade order, when shells count with their routes', () => { + // Given: a root layout entry importing a header, and three page entries + // When: real webpack builds with and without route shells + const off = build('off') + const on = build('on') + const again = build('on') + + // Then: as its own route, the layout's header kept per-file names + expect(sheetWith(off, 'color:orange')).not.toBe('devup-ui.css') + expect(off['devup-ui.css']).not.toContain('color:white') + // ...counted with the pages, it joins the shared sheet with short names + const shared = on['devup-ui.css']! + expect(shared).toMatch(/\.[a-z]+\{color:white\}/) + expect(shared).toMatch(/\.[a-z]+:hover\{color:orange\}/) + // Base rules, then the breakpoint, then the selector + const base = shared.indexOf('{color:white}') + const media = shared.indexOf('@media(min-width:768px){') + const hover = shared.indexOf(':hover{color:orange}') + expect(base).toBeGreaterThan(-1) + expect(media).toBeGreaterThan(base) + expect(shared.indexOf('{font-size:72px}')).toBeGreaterThan(media) + expect(hover).toBeGreaterThan(media) + // The header's own sheet keeps only the shared import, ahead of nothing + const headerSheet = sheetWith(off, 'color:orange')! + expect(on[headerSheet]).toMatch(/@import "\.\/devup-ui\.css";$/) + // Every other per-file sheet is unchanged and still imports the shared one first + for (const name of Object.keys(off)) + if (name !== headerSheet && name !== 'devup-ui.css') { + expect(on[name]).toBe(off[name]) + expect(on[name]).toContain('@import "./devup-ui.css";') + } + // Deterministic + expect(again).toEqual(on) +}, 120000) + +it('leaves a build without route shells byte-identical', () => { + expect(build('on', 'none')).toEqual(build('off', 'none')) +}, 120000) diff --git a/packages/webpack-plugin/src/plugin.ts b/packages/webpack-plugin/src/plugin.ts index 04c009b2d..6d2fb805d 100644 --- a/packages/webpack-plugin/src/plugin.ts +++ b/packages/webpack-plugin/src/plugin.ts @@ -41,6 +41,7 @@ import { type StylexStyleResolution, tailwindCssFiles, type WasmImportAliases, + withRouteShells, withTailwindCss, } from '@devup-ui/plugin-utils' import { type Compiler, type RuleSetRule } from 'webpack' @@ -93,6 +94,13 @@ export interface DevupUIWebpackPluginOptions extends Pick< importAliases?: ImportAliases /** Adapter-owned complete extraction set; undefined keeps generic entry reachability. */ readonly productionPrewarmFiles?: readonly string[] + /** + * Count a Next.js route shell that wraps every route (the root `layout` or + * `template`, `pages/_app`) as part of those routes rather than as a route + * of its own when hoisting atoms. Set by the Next.js plugin for production + * builds. + */ + readonly routeShells?: boolean } export class DevupUIWebpackPlugin { @@ -130,6 +138,7 @@ export class DevupUIWebpackPlugin { stylex, atomHoist = 2, productionPrewarmFiles, + routeShells = false, importAliases: userImportAliases, }: Partial = {}) { this.normalizedShorthands = normalizeShorthands(shorthands ?? {}) @@ -160,6 +169,7 @@ export class DevupUIWebpackPlugin { shorthands, atomHoist, productionPrewarmFiles: undefined, + routeShells, } this.sheetFile = '' this.classMapFile = '' @@ -290,14 +300,17 @@ export class DevupUIWebpackPlugin { }) this.compiler.importCanonicalMap(canonicalMap) if (atomHoist === undefined) return discovered + const reach = this.options.routeShells + ? withRouteShells(graph, routes, cwd) + : { graph, routes } const plan = planAtomHoist( canonicalMap, computeFileReach({ srcDir: cwd, cwd, keyBy: 'cwd-relative', - graph, - entries: routes, + graph: reach.graph, + entries: reach.routes, }), atomHoist, )