From a1014f50151133ee9bf85857898c029f21a68123 Mon Sep 17 00:00:00 2001 From: ladybluenotes Date: Sun, 6 Sep 2026 10:42:50 -0700 Subject: [PATCH 1/3] fix(router-plugin): omit browser warnings from production bundles --- .changeset/calm-tables-warn.md | 5 ++ .../src/core/code-splitter/compilers.ts | 5 +- .../src/core/router-code-splitter-plugin.ts | 5 +- .../tests/router-plugin-context.test.ts | 78 +++++++++++++++++++ 4 files changed, 89 insertions(+), 4 deletions(-) create mode 100644 .changeset/calm-tables-warn.md diff --git a/.changeset/calm-tables-warn.md b/.changeset/calm-tables-warn.md new file mode 100644 index 0000000000..53bb5d49e1 --- /dev/null +++ b/.changeset/calm-tables-warn.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-plugin': patch +--- + +Respect bundler production mode when injecting code-splitting warnings into browser bundles, even when the host `NODE_ENV` is unset or different. Build-console warnings remain available. diff --git a/packages/router-plugin/src/core/code-splitter/compilers.ts b/packages/router-plugin/src/core/code-splitter/compilers.ts index 89cdae41ad..ce68423eff 100644 --- a/packages/router-plugin/src/core/code-splitter/compilers.ts +++ b/packages/router-plugin/src/core/code-splitter/compilers.ts @@ -364,6 +364,7 @@ function removeSharedDeclarations(ast: t.File, sharedBindings: Set) { export function compileCodeSplitReferenceRoute( opts: ParseAstOptions & CompileCodeSplitReferenceRouteOptions & { + isProduction?: boolean compilerPlugins?: Array }, ): GeneratorResult | null { @@ -847,8 +848,8 @@ export function compileCodeSplitReferenceRoute( ) console.warn(warningMessage) - // append this warning to the file using a template - if (process.env.NODE_ENV !== 'production') { + // The bundler's production mode can differ from the host NODE_ENV. + if (!(opts.isProduction ?? process.env.NODE_ENV === 'production')) { const warningTemplate = template.statement( `console.warn(${JSON.stringify(warningMessage)})`, )() diff --git a/packages/router-plugin/src/core/router-code-splitter-plugin.ts b/packages/router-plugin/src/core/router-code-splitter-plugin.ts index f1f75d4f3c..2b98fc3f1c 100644 --- a/packages/router-plugin/src/core/router-code-splitter-plugin.ts +++ b/packages/router-plugin/src/core/router-code-splitter-plugin.ts @@ -186,6 +186,7 @@ export function createRouterCodeSplitterPlugin( targetFramework: userConfig.target, filename: id, id, + isProduction, deleteNodes: userConfig.codeSplittingOptions?.deleteNodes ? new Set(userConfig.codeSplittingOptions.deleteNodes) : undefined, @@ -332,13 +333,13 @@ export function createRouterCodeSplitterPlugin( }, rspack(compiler) { - isProduction = compiler.options.mode === 'production' + isProduction = (compiler.options.mode ?? 'production') === 'production' ROOT = process.cwd() initUserConfig() }, webpack(compiler) { - isProduction = compiler.options.mode === 'production' + isProduction = (compiler.options.mode ?? 'production') === 'production' ROOT = process.cwd() initUserConfig() }, diff --git a/packages/router-plugin/tests/router-plugin-context.test.ts b/packages/router-plugin/tests/router-plugin-context.test.ts index ecb6e7e167..aeeddd0a30 100644 --- a/packages/router-plugin/tests/router-plugin-context.test.ts +++ b/packages/router-plugin/tests/router-plugin-context.test.ts @@ -90,6 +90,84 @@ function countProgramHotDeclarations(code: string) { } describe('router plugin context', () => { + describe.each(['webpack', 'rspack', 'vite'] as const)( + '%s browser warnings', + (bundler) => { + it.each([ + { mode: 'production', nodeEnv: undefined }, + { mode: 'production', nodeEnv: 'development' }, + { mode: 'production', nodeEnv: 'production' }, + { mode: 'development', nodeEnv: undefined }, + { mode: 'development', nodeEnv: 'development' }, + { mode: 'development', nodeEnv: 'production' }, + ...(bundler === 'vite' + ? [] + : ([ + { mode: undefined, nodeEnv: undefined }, + { mode: undefined, nodeEnv: 'development' }, + { mode: undefined, nodeEnv: 'production' }, + { mode: 'none', nodeEnv: undefined }, + { mode: 'none', nodeEnv: 'development' }, + { mode: 'none', nodeEnv: 'production' }, + ] as const)), + ] as const)( + 'uses $mode mode with NODE_ENV=$nodeEnv', + async ({ mode, nodeEnv }) => { + vi.stubEnv('NODE_ENV', nodeEnv) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + try { + const routeFile = normalizePath( + path.join(process.cwd(), 'src/routes/exported.tsx'), + ) + const context = createRouterPluginContext() + context.routesByFile.set(routeFile, { routeId: '/exported' }) + const plugin = getReferencePlugin( + createRouterCodeSplitterPlugin( + { target: 'react', codeSplittingOptions: { addHmr: false } }, + context, + ), + ) + + if (bundler === 'vite') { + await configurePlugin( + plugin, + mode === 'production' ? 'build' : 'serve', + ) + } else { + plugin[bundler]!({ options: { mode } } as never) + } + + const code = getCode( + await transformReferenceRoute( + plugin, + `import { createFileRoute } from '@tanstack/react-router' +export function ExportedComponent() { return null } +export const Route = createFileRoute('/exported')({ + component: ExportedComponent, + errorComponent: () => null, +})`, + routeFile, + ), + ) + + expect(code).toContain('export function ExportedComponent') + expect(code).toContain('?tsr-split=errorComponent') + expect(code?.includes('console.warn')).toBe( + mode === 'development' || mode === 'none', + ) + expect(warn).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining('These exports'), + ) + } finally { + warn.mockRestore() + vi.unstubAllEnvs() + } + }, + ) + }, + ) + it.each([ { mode: 'production', production: true }, { mode: 'development with addHmr disabled', production: false }, From 15109d41a3be46cf9554720c3cc840de6e2105ed Mon Sep 17 00:00:00 2001 From: Sheraff Date: Wed, 4 Nov 2026 08:22:15 +0100 Subject: [PATCH 2/3] fix(router-plugin): only the bundler's mode keeps the warning out of the page The code splitter always passes isProduction, so the NODE_ENV fallback in the compiler was reachable only from direct test calls. The changeset now names the bug users see. Co-Authored-By: Claude Opus 5.5 --- .changeset/calm-tables-warn.md | 2 +- .../src/core/code-splitter/compilers.ts | 5 +- .../tests/router-plugin-context.test.ts | 78 ------------------- 3 files changed, 4 insertions(+), 81 deletions(-) diff --git a/.changeset/calm-tables-warn.md b/.changeset/calm-tables-warn.md index 53bb5d49e1..5a72b4794c 100644 --- a/.changeset/calm-tables-warn.md +++ b/.changeset/calm-tables-warn.md @@ -2,4 +2,4 @@ '@tanstack/router-plugin': patch --- -Respect bundler production mode when injecting code-splitting warnings into browser bundles, even when the host `NODE_ENV` is unset or different. Build-console warnings remain available. +fix: webpack and Rspack production builds no longer put the code splitter's "will not be code-split" warning, with the route file's absolute path, into the client bundle when the build process's `NODE_ENV` isn't `production`. The bundler's mode decides, and a config without `mode` counts as production, as it does for webpack and Rspack. The warning still prints in the build output. diff --git a/packages/router-plugin/src/core/code-splitter/compilers.ts b/packages/router-plugin/src/core/code-splitter/compilers.ts index 8d836bfa49..0cd783a58a 100644 --- a/packages/router-plugin/src/core/code-splitter/compilers.ts +++ b/packages/router-plugin/src/core/code-splitter/compilers.ts @@ -848,8 +848,9 @@ export function compileCodeSplitReferenceRoute( ) console.warn(warningMessage) - // The bundler's production mode can differ from the host NODE_ENV. - if (!(opts.isProduction ?? process.env.NODE_ENV === 'production')) { + // Development builds log it in the page too. The bundler's mode decides, + // not the build process's NODE_ENV, which webpack never sets. + if (!opts.isProduction) { const warningTemplate = template.statement( `console.warn(${JSON.stringify(warningMessage)})`, )() diff --git a/packages/router-plugin/tests/router-plugin-context.test.ts b/packages/router-plugin/tests/router-plugin-context.test.ts index 1c244dc293..d3fb0563e6 100644 --- a/packages/router-plugin/tests/router-plugin-context.test.ts +++ b/packages/router-plugin/tests/router-plugin-context.test.ts @@ -90,84 +90,6 @@ function countProgramHotDeclarations(code: string) { } describe('router plugin context', () => { - describe.each(['webpack', 'rspack', 'vite'] as const)( - '%s browser warnings', - (bundler) => { - it.each([ - { mode: 'production', nodeEnv: undefined }, - { mode: 'production', nodeEnv: 'development' }, - { mode: 'production', nodeEnv: 'production' }, - { mode: 'development', nodeEnv: undefined }, - { mode: 'development', nodeEnv: 'development' }, - { mode: 'development', nodeEnv: 'production' }, - ...(bundler === 'vite' - ? [] - : ([ - { mode: undefined, nodeEnv: undefined }, - { mode: undefined, nodeEnv: 'development' }, - { mode: undefined, nodeEnv: 'production' }, - { mode: 'none', nodeEnv: undefined }, - { mode: 'none', nodeEnv: 'development' }, - { mode: 'none', nodeEnv: 'production' }, - ] as const)), - ] as const)( - 'uses $mode mode with NODE_ENV=$nodeEnv', - async ({ mode, nodeEnv }) => { - vi.stubEnv('NODE_ENV', nodeEnv) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - try { - const routeFile = normalizePath( - path.join(process.cwd(), 'src/routes/exported.tsx'), - ) - const context = createRouterPluginContext() - context.routesByFile.set(routeFile, { routeId: '/exported' }) - const plugin = getReferencePlugin( - createRouterCodeSplitterPlugin( - { target: 'react', codeSplittingOptions: { addHmr: false } }, - context, - ), - ) - - if (bundler === 'vite') { - await configurePlugin( - plugin, - mode === 'production' ? 'build' : 'serve', - ) - } else { - plugin[bundler]!({ options: { mode } } as never) - } - - const code = getCode( - await transformReferenceRoute( - plugin, - `import { createFileRoute } from '@tanstack/react-router' -export function ExportedComponent() { return null } -export const Route = createFileRoute('/exported')({ - component: ExportedComponent, - errorComponent: () => null, -})`, - routeFile, - ), - ) - - expect(code).toContain('export function ExportedComponent') - expect(code).toContain('?tsr-split=errorComponent') - expect(code?.includes('console.warn')).toBe( - mode === 'development' || mode === 'none', - ) - expect(warn).toHaveBeenCalledExactlyOnceWith( - expect.stringContaining('These exports'), - ) - } finally { - warn.mockRestore() - vi.unstubAllEnvs() - } - }, - ) - }, - ) - it('splits parenthesized route factories, option values, and grouping arrays', async () => { const routeFile = normalizePath( path.join(process.cwd(), 'src/routes/wrapped.tsx'), From 96d73b86909df317b5c0f2c8ed2aaaf93794b7e8 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Wed, 4 Nov 2026 08:22:15 +0100 Subject: [PATCH 3/3] test(router-plugin): real webpack and Rspack production builds ship no splitter warning Builds an app whose route exports its component, with mode 'production' and with mode left out, and checks that no emitted JS names the app's absolute path. Fails on main. Replaces the fake-compiler matrix in router-plugin-context.test.ts. Co-Authored-By: Claude Opus 5.5 --- .../tests/production-warnings.test.ts | 209 ++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 packages/router-plugin/tests/production-warnings.test.ts diff --git a/packages/router-plugin/tests/production-warnings.test.ts b/packages/router-plugin/tests/production-warnings.test.ts new file mode 100644 index 0000000000..1ace6edf50 --- /dev/null +++ b/packages/router-plugin/tests/production-warnings.test.ts @@ -0,0 +1,209 @@ +/** + * A production client build ships none of the code splitter's development + * warnings, whatever the build process's `NODE_ENV` (Vitest sets it to + * `test`, which behaves like a shell without it): the bundler's mode + * decides, and webpack and Rspack build in production when `mode` is left + * out. Such a warning would log in every visitor's console, with the + * absolute path of the route file on the build machine. + */ +import { + mkdir, + mkdtemp, + readFile, + readdir, + rm, + writeFile, +} from 'node:fs/promises' +import path from 'node:path' +import { rspack } from '@rsbuild/core' +import webpack from 'webpack' +import { describe, expect, test, vi } from 'vitest' + +const timeout = 60_000 + +/** + * The exported component stays in the route module unless the code splitter + * can split exports; the error component is split either way. + */ +const routeSource = `import { createFileRoute } from '@tanstack/react-router' + +export function ExportedPage() { + return 'MARK_EXPORTED_PAGE' +} + +function ErrorPage() { + return 'MARK_ERROR_PAGE' +} + +export const Route = createFileRoute('/')({ + component: ExportedPage, + errorComponent: ErrorPage, +}) +` + +const rootSource = `import { createRootRoute } from '@tanstack/react-router' +export const Route = createRootRoute({}) +` + +/** Writes `files` into a new app directory inside the package. */ +async function createApp(files: Record) { + // Keep the app inside the package so runtime imports resolve. + const root = await mkdtemp(path.join(__dirname, '.production-warnings-')) + await mkdir(path.join(root, 'routes')) + for (const [file, code] of Object.entries(files)) { + await writeFile(path.join(root, file), code) + } + return root +} + +function routerOptions(root: string) { + return { + target: 'react', + routesDirectory: path.join(root, 'routes'), + generatedRouteTree: path.join(root, 'routeTree.gen.ts'), + autoCodeSplitting: true, + } as const +} + +/** A client build of `entry` in `mode` (left out when undefined), unminified. */ +function compilerConfig( + root: string, + entry: string, + mode: 'production' | undefined, +) { + return { + context: root, + ...(mode ? { mode } : {}), + target: 'web', + entry: `./${entry}`, + output: { path: path.join(root, 'dist') }, + optimization: { minimize: false }, + } as const +} + +interface Compiler { + run: ( + callback: ( + error: Error | null, + stats?: { + hasErrors: () => boolean + toString: (options: object) => string + }, + ) => void, + ) => void + close: (callback: (error?: Error | null) => void) => void +} + +/** Runs one build and settles once the compiler has closed. */ +function runCompiler(compiler: Compiler) { + return new Promise((resolve, reject) => { + compiler.run((error, stats) => { + // The test removes the app afterwards: wait for the compiler to finish. + compiler.close((closeError) => { + if (error ?? closeError) { + reject(error ?? closeError) + } else if (stats?.hasErrors()) { + reject(new Error(stats.toString({ all: false, errors: true }))) + } else { + resolve() + } + }) + }) + }) +} + +const bundlers = [ + { + name: 'webpack', + // webpack parses no TypeScript: the router plugin is the only loader. + extension: 'js', + async build(root: string, entry: string, mode: 'production' | undefined) { + const { tanstackRouter } = await import('../src/webpack') + await runCompiler( + webpack({ + ...compilerConfig(root, entry, mode), + // The test app is not part of the package's TypeScript project. + resolve: { tsconfig: false }, + plugins: [tanstackRouter(routerOptions(root))], + }), + ) + }, + }, + { + name: 'rspack', + // As in Rsbuild: SWC compiles the router plugin's output. + extension: 'tsx', + async build(root: string, entry: string, mode: 'production' | undefined) { + const { tanstackRouter } = await import('../src/rspack') + await runCompiler( + rspack({ + ...compilerConfig(root, entry, mode), + module: { + rules: [ + { + test: /\.tsx?$/, + loader: 'builtin:swc-loader', + options: { + jsc: { parser: { syntax: 'typescript', tsx: true } }, + }, + type: 'javascript/auto', + }, + ], + }, + plugins: [tanstackRouter(routerOptions(root))], + }), + ) + }, + }, +] as const + +describe.each(bundlers)('$name build', (bundler) => { + test.each([ + { label: "mode: 'production'", mode: 'production' }, + { label: 'mode left out', mode: undefined }, + ] as const)( + 'with $label, the client JS logs no warning about an exported component', + async ({ mode }) => { + const routeFile = `routes/index.${bundler.extension}` + const entry = `entry.${bundler.extension}` + const root = await createApp({ + [`routes/__root.${bundler.extension}`]: rootSource, + [routeFile]: routeSource, + [entry]: `import { Route } from './${routeFile}'\nglobalThis.route = Route\n`, + }) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + await bundler.build(root, entry, mode) + const warned = warn.mock.calls.some((args) => + args.some((arg) => String(arg).includes('ExportedPage')), + ) + const dist = path.join(root, 'dist') + const chunks = new Map() + for (const file of await readdir(dist)) { + if (file.endsWith('.js')) { + chunks.set(file, await readFile(path.join(dist, file), 'utf8')) + } + } + expect( + chunks.get('main.js'), + 'the error component is split', + ).not.toContain('MARK_ERROR_PAGE') + // An exported component kept in the route module is reported. + const split = !chunks.get('main.js')!.includes('MARK_EXPORTED_PAGE') + expect(split || warned, 'split, or reported by the build').toBe(true) + // The app's directory name appears only in absolute paths. + const linesNamingTheApp = [...chunks].flatMap(([file, code]) => + code + .split('\n') + .filter((line) => line.includes(path.basename(root))) + .map((line) => `${file}: ${line.trim()}`), + ) + expect(linesNamingTheApp).toEqual([]) + } finally { + warn.mockRestore() + await rm(root, { recursive: true, force: true }) + } + }, + timeout, + ) +})