Skip to content

Commit f7f0025

Browse files
fix(start): include Vite style.css when cssCodeSplit is disabled (#7191)
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
1 parent 4b8df29 commit f7f0025

10 files changed

Lines changed: 320 additions & 105 deletions

File tree

‎.changeset/lucky-pandas-share.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/start-plugin-core': patch
3+
---
4+
5+
Fix missing CSS module assets in TanStack Start production manifests when Vite `build.cssCodeSplit` is disabled.

‎e2e/react-start/css-modules/package.json‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@
1919
"test:e2e:dev:nitro": "MODE=dev VITE_CONFIG=nitro playwright test --project=chromium",
2020
"test:e2e:dev:basepath": "MODE=dev VITE_CONFIG=basepath playwright test --project=chromium",
2121
"_test:e2e:dev:cloudflare": "MODE=dev VITE_CONFIG=cloudflare playwright test --project=chromium",
22-
"test:e2e:prod": "MODE=prod playwright test --project=chromium",
22+
"test:e2e:prod:default": "MODE=prod playwright test --project=chromium",
23+
"test:e2e:prod": "pnpm run test:e2e:prod:default && pnpm run test:e2e:prod:css-code-split-false",
24+
"test:e2e:prod:css-code-split-false": "MODE=prod VITE_CSS_CODE_SPLIT=false playwright test tests/css.prod.spec.ts --project=chromium",
2325
"test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev && pnpm run test:e2e:prod",
2426
"test:e2e:nitro": "rm -rf port*.txt; pnpm run test:e2e:dev:nitro",
2527
"test:e2e:basepath": "rm -rf port*.txt; pnpm run test:e2e:dev:basepath",
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import { expect } from '@playwright/test'
2+
import { test } from '@tanstack/router-e2e-utils'
3+
4+
test.skip(process.env.MODE !== 'prod', 'Prod-only coverage')
5+
test.skip(
6+
process.env.VITE_CSS_CODE_SPLIT !== 'false',
7+
'Requires cssCodeSplit=false mode',
8+
)
9+
10+
test.describe('CSS modules with cssCodeSplit disabled', () => {
11+
test.describe('with JavaScript disabled', () => {
12+
test.use({ javaScriptEnabled: false })
13+
14+
test('CSS modules are applied on initial page load', async ({ page }) => {
15+
await page.goto('/modules')
16+
17+
const card = page.getByTestId('module-card')
18+
await expect(card).toBeVisible()
19+
20+
const className = await card.getAttribute('class')
21+
expect(className).toBeTruthy()
22+
expect(className).not.toBe('card')
23+
expect(className!.length).toBeGreaterThan(5)
24+
25+
const backgroundColor = await card.evaluate(
26+
(el) => getComputedStyle(el).backgroundColor,
27+
)
28+
expect(backgroundColor).toBe('rgb(240, 253, 244)')
29+
30+
const padding = await card.evaluate((el) => getComputedStyle(el).padding)
31+
expect(padding).toBe('16px')
32+
33+
const borderRadius = await card.evaluate(
34+
(el) => getComputedStyle(el).borderRadius,
35+
)
36+
expect(borderRadius).toBe('8px')
37+
})
38+
})
39+
40+
test('CSS modules styles persist after hydration', async ({ page }) => {
41+
await page.goto('/modules')
42+
43+
const card = page.getByTestId('module-card')
44+
await expect(card).toBeVisible()
45+
46+
await expect(async () => {
47+
const backgroundColor = await card.evaluate(
48+
(el) => getComputedStyle(el).backgroundColor,
49+
)
50+
expect(backgroundColor).toBe('rgb(240, 253, 244)')
51+
}).toPass({ timeout: 5000 })
52+
})
53+
54+
test('styles work correctly after client-side navigation', async ({
55+
page,
56+
}) => {
57+
await page.goto('/')
58+
59+
const globalElement = page.getByTestId('global-styled')
60+
await expect(globalElement).toBeVisible()
61+
62+
let backgroundColor = await globalElement.evaluate(
63+
(el) => getComputedStyle(el).backgroundColor,
64+
)
65+
expect(backgroundColor).toBe('rgb(59, 130, 246)')
66+
67+
await page.getByTestId('nav-modules').click()
68+
await page.waitForURL('**/modules')
69+
70+
const card = page.getByTestId('module-card')
71+
await expect(card).toBeVisible()
72+
73+
await expect(async () => {
74+
const backgroundColor = await card.evaluate(
75+
(el) => getComputedStyle(el).backgroundColor,
76+
)
77+
expect(backgroundColor).toBe('rgb(240, 253, 244)')
78+
}).toPass({ timeout: 5000 })
79+
})
80+
})

‎e2e/react-start/css-modules/vite.config.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@ import viteReact from '@vitejs/plugin-react'
55
// Environment variables for different test configurations:
66
// - VITE_BASE_PATH: Set to '/my-app' for basepath testing
77
// - VITE_USE_NITRO: Set to 'true' to enable Nitro server
8+
// - VITE_CSS_CODE_SPLIT: Set to 'false' to disable CSS code splitting in prod
89
const basePath = process.env.VITE_BASE_PATH
910
const useNitro = process.env.VITE_USE_NITRO === 'true'
11+
const cssCodeSplit = process.env.VITE_CSS_CODE_SPLIT !== 'false'
1012

1113
export default defineConfig(async () => {
1214
// Dynamically import nitro only when needed to avoid loading it when not used
@@ -18,6 +20,9 @@ export default defineConfig(async () => {
1820
server: {
1921
port: 3000,
2022
},
23+
build: {
24+
cssCodeSplit,
25+
},
2126
plugins: [
2227
// Nitro is placed BEFORE tanstackStart to test that our CSS middleware
2328
// works regardless of plugin order (nitro has a catch-all middleware)

‎packages/start-plugin-core/src/start-manifest-plugin/manifestBuilder.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,9 @@ export function buildStartManifest(options: {
152152
clientBuild: NormalizedClientBuild
153153
routeTreeRoutes: RouteTreeRoutes
154154
basePath: string
155+
additionalRouteAssets?: Partial<
156+
Record<string, ReadonlyArray<RouterManagedTag>>
157+
>
155158
}): StartManifest {
156159
const scannedChunks = scanClientChunks(options.clientBuild)
157160
const assetResolvers = createManifestAssetResolvers(options.basePath)
@@ -162,6 +165,7 @@ export function buildStartManifest(options: {
162165
chunksByFileName: scannedChunks.chunksByFileName,
163166
entryChunk: scannedChunks.entryChunk,
164167
assetResolvers,
168+
additionalRouteAssets: options.additionalRouteAssets,
165169
})
166170

167171
dedupeNestedRouteManifestEntries(rootRouteId, routes[rootRouteId]!, routes)
@@ -352,6 +356,9 @@ export function buildRouteManifestRoutes(options: {
352356
chunksByFileName: ReadonlyMap<string, NormalizedClientChunk>
353357
entryChunk: NormalizedClientChunk
354358
assetResolvers: ManifestAssetResolvers
359+
additionalRouteAssets?: Partial<
360+
Record<string, ReadonlyArray<RouterManagedTag>>
361+
>
355362
}) {
356363
const routes: Record<string, RouteTreeRoute> = {}
357364
const getChunkCssAssets = createChunkCssAssetCollector({
@@ -396,6 +403,25 @@ export function buildRouteManifestRoutes(options: {
396403
getChunkPreloads: options.assetResolvers.getChunkPreloads,
397404
})
398405

406+
if (options.additionalRouteAssets) {
407+
for (const [routeId, assets] of Object.entries(
408+
options.additionalRouteAssets,
409+
)) {
410+
if (!assets || assets.length === 0) {
411+
continue
412+
}
413+
414+
if (!(routeId in options.routeTreeRoutes)) {
415+
throw new Error(
416+
`expected additionalRouteAssets routeId to exist in routeTreeRoutes: ${routeId}`,
417+
)
418+
}
419+
420+
const route = (routes[routeId] = routes[routeId] || {})
421+
route.assets = appendUniqueAssets(route.assets, [...assets])
422+
}
423+
}
424+
399425
return routes
400426
}
401427

‎packages/start-plugin-core/src/vite/plugin.ts‎

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ import {
2222
import { devServerPlugin } from './dev-server-plugin/plugin'
2323
import { previewServerPlugin } from './preview-server-plugin/plugin'
2424
import {
25-
createCaptureClientBuildPlugin,
2625
createDevBaseRewritePlugin,
2726
createPostBuildPlugin,
2827
createVirtualClientEntryPlugin,
@@ -36,12 +35,10 @@ import {
3635
} from './output-directory'
3736
import { postServerBuild } from './post-server-build'
3837
import { serializationAdaptersPlugin } from './serialization-adapters-plugin'
39-
import type { NormalizedClientBuild } from '../types'
4038
import type {
4139
TanStackStartVitePluginCoreOptions,
4240
ViteRscForwardSsrResolverStrategy,
4341
} from './types'
44-
import type { StartEnvironmentName } from '../constants'
4542
import type { TanStackStartViteInputConfig } from './schema'
4643
import type { PluginOption } from 'vite'
4744

@@ -64,16 +61,6 @@ export function tanStackStartVite(
6461
// we install a URL rewrite middleware instead of erroring.
6562
let needsDevBaseRewrite = false
6663

67-
const capturedClientBuild: Partial<
68-
Record<StartEnvironmentName, NormalizedClientBuild>
69-
> = {}
70-
71-
function getClientBuild(
72-
envName: StartEnvironmentName,
73-
): NormalizedClientBuild | undefined {
74-
return capturedClientBuild[envName]
75-
}
76-
7764
const environments: Array<{
7865
name: string
7966
type: 'client' | 'server'
@@ -242,7 +229,6 @@ export function tanStackStartVite(
242229
getClientEntry: () => configContext.resolveEntries().entryPaths.client,
243230
}),
244231
startManifestPlugin({
245-
getClientBuild: () => getClientBuild(START_ENVIRONMENT_NAMES.client),
246232
getConfig,
247233
}),
248234
// When the vite base and router basepath are misaligned (e.g. base: '/_ui/', basepath: '/'),
@@ -266,9 +252,6 @@ export function tanStackStartVite(
266252
serializationAdaptersPlugin({
267253
adapters: corePluginOpts.serializationAdapters,
268254
}),
269-
createCaptureClientBuildPlugin({
270-
capturedClientBuild,
271-
}),
272255
]
273256
}
274257

‎packages/start-plugin-core/src/vite/plugins.ts‎

Lines changed: 2 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,7 @@
11
import { normalizePath } from 'vite'
2-
import { ENTRY_POINTS, START_ENVIRONMENT_NAMES } from '../constants'
2+
import { ENTRY_POINTS } from '../constants'
33
import { createVirtualModule } from './createVirtualModule'
4-
import { normalizeViteClientBuild } from './start-manifest-plugin/normalized-client-build'
5-
import type {
6-
GetConfigFn,
7-
NormalizedClientBuild,
8-
ResolvedStartConfig,
9-
} from '../types'
10-
import type { StartEnvironmentName } from '../constants'
4+
import type { GetConfigFn, ResolvedStartConfig } from '../types'
115
import type { PluginOption, ViteBuilder } from 'vite'
126

137
export function createVirtualClientEntryPlugin(opts: {
@@ -69,28 +63,3 @@ export function createDevBaseRewritePlugin(opts: {
6963
},
7064
}
7165
}
72-
73-
export function createCaptureClientBuildPlugin(opts: {
74-
capturedClientBuild: Partial<
75-
Record<StartEnvironmentName, NormalizedClientBuild>
76-
>
77-
}): PluginOption {
78-
return {
79-
name: 'tanstack-start:core:capture-bundle',
80-
applyToEnvironment(environment) {
81-
return environment.name === START_ENVIRONMENT_NAMES.client
82-
},
83-
enforce: 'post',
84-
generateBundle(_options, bundle) {
85-
const environment = this.environment.name as StartEnvironmentName
86-
87-
if (environment !== START_ENVIRONMENT_NAMES.client) {
88-
throw new Error(
89-
`Unexpected environment for client build capture: ${environment}`,
90-
)
91-
}
92-
93-
opts.capturedClientBuild[environment] = normalizeViteClientBuild(bundle)
94-
},
95-
}
96-
}

‎packages/start-plugin-core/src/vite/start-manifest-plugin/normalized-client-build.ts‎

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ export function normalizeViteClientBuild(
4242
const cssFilesBySourcePath = new Map<string, Array<string>>()
4343

4444
for (const chunk of chunksByFileName.values()) {
45+
const bundleEntry = clientBundle[chunk.fileName] as Rollup.OutputChunk
46+
4547
if (chunk.isEntry) {
4648
if (entryChunkFileName) {
4749
throw new Error(
@@ -60,22 +62,19 @@ export function normalizeViteClientBuild(
6062
chunkFileNames.push(chunk.fileName)
6163
}
6264

63-
const bundleEntry = clientBundle[chunk.fileName]
64-
if (bundleEntry?.type === 'chunk') {
65-
for (const moduleId of bundleEntry.moduleIds) {
66-
const queryIndex = moduleId.indexOf('?')
67-
const sourcePath =
68-
queryIndex >= 0 ? moduleId.slice(0, queryIndex) : moduleId
69-
if (!sourcePath) continue
70-
71-
const existing = cssFilesBySourcePath.get(sourcePath)
72-
cssFilesBySourcePath.set(
73-
sourcePath,
74-
existing
75-
? Array.from(new Set([...existing, ...chunk.css]))
76-
: chunk.css.slice(),
77-
)
78-
}
65+
for (const moduleId of bundleEntry.moduleIds) {
66+
const queryIndex = moduleId.indexOf('?')
67+
const sourcePath =
68+
queryIndex >= 0 ? moduleId.slice(0, queryIndex) : moduleId
69+
if (!sourcePath) continue
70+
71+
const existing = cssFilesBySourcePath.get(sourcePath)
72+
cssFilesBySourcePath.set(
73+
sourcePath,
74+
existing
75+
? Array.from(new Set([...existing, ...chunk.css]))
76+
: chunk.css.slice(),
77+
)
7978
}
8079
}
8180

0 commit comments

Comments
 (0)