Skip to content

Commit e16ff3a

Browse files
fix(build): map CSS chunks in chunk import maps (fix #22946) (#22947)
Co-authored-by: sapphi-red <[email protected]>
1 parent 55bba7b commit e16ff3a

6 files changed

Lines changed: 122 additions & 2 deletions

File tree

‎packages/vite/src/node/plugins/css.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
480480
let codeSplitEmitQueue = createSerialPromiseQueue<string>()
481481
const urlEmitQueue = createSerialPromiseQueue<unknown>()
482482
let pureCssChunks: Set<RenderedChunk>
483+
let chunkCssReferences: Map<string, string>
483484

484485
// when there are multiple rollup outputs and extracting CSS, only emit once,
485486
// since output formats have no effect on the generated CSS.
@@ -536,6 +537,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
536537
renderStart() {
537538
// Ensure new caches for every build (i.e. rebuilding in watch mode)
538539
pureCssChunks = new Set<RenderedChunk>()
540+
chunkCssReferences = new Map<string, string>()
539541
hasEmitted = false
540542
chunkCSSMap = new Map()
541543
codeSplitEmitQueue = createSerialPromiseQueue()
@@ -930,6 +932,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
930932
originalFileName,
931933
source: chunkCSS,
932934
})
935+
chunkCssReferences.set(chunk.fileName, referenceId)
933936
if (isEntry) {
934937
cssEntriesMap
935938
.get(this.environment)!
@@ -1067,6 +1070,39 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
10671070
}
10681071
}
10691072

1073+
// With `cssCodeSplit: false`, CSS is emitted as a single stylesheet in the HTML,
1074+
// so this per-chunk import map handling is irrelevant.
1075+
if (config.build.chunkImportMap && chunkCssReferences.size) {
1076+
// The import map hash identifies the JS chunk independently of its content.
1077+
// Since each chunk has at most one extracted CSS sidecar, we can reuse that
1078+
// stable identity with a `.css` extension while mapping it to the CSS content hash.
1079+
const importMap = getImportMap(bundle, config)!
1080+
const importMapReverseMapping = Object.fromEntries(
1081+
Object.entries(importMap.mapping).map(([k, v]) => [v, k]),
1082+
)
1083+
const chunksByPreliminaryFileName = new Map(
1084+
Object.values(bundle)
1085+
.filter((output): output is OutputChunk => output.type === 'chunk')
1086+
.map((chunk) => [chunk.preliminaryFileName, chunk]),
1087+
)
1088+
1089+
for (const [chunkFileName, referenceId] of chunkCssReferences) {
1090+
const chunk = chunksByPreliminaryFileName.get(chunkFileName)
1091+
if (!chunk) continue
1092+
1093+
const stableChunkFileName =
1094+
importMapReverseMapping[chunk.fileName] ?? chunk.fileName
1095+
const extension = path.posix.extname(stableChunkFileName)
1096+
const stableCssFileName = `${stableChunkFileName.slice(
1097+
0,
1098+
extension ? -extension.length : undefined,
1099+
)}.css`
1100+
importMap.content.imports[config.base + stableCssFileName] =
1101+
config.base + this.getFileName(referenceId)
1102+
}
1103+
importMap.asset.source = JSON.stringify(importMap.content)
1104+
}
1105+
10701106
// remove empty css chunks and their imports
10711107
if (pureCssChunks.size) {
10721108
// map each pure css chunk (rendered chunk) to it's corresponding bundle

‎packages/vite/src/node/plugins/html.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1680,6 +1680,7 @@ export function getImportMap(
16801680
):
16811681
| {
16821682
asset: OutputAsset
1683+
content: { imports: Record<string, string> }
16831684
/** import map entries with the base stripped (placeholder name -> real name) */
16841685
mapping: Record<string, string>
16851686
}
@@ -1698,5 +1699,5 @@ export function getImportMap(
16981699
v.slice(config.base.length),
16991700
]),
17001701
)
1701-
return { asset, mapping }
1702+
return { asset, content, mapping }
17021703
}

‎playground/chunk-importmap/__tests__/chunk-importmap.spec.ts‎

Lines changed: 79 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { expect, test } from 'vitest'
2-
import { browserLogs, getColor, page } from '~utils'
2+
import type { OutputAsset, OutputChunk, RolldownOutput } from 'rolldown'
3+
import { build } from 'vite'
4+
import { browserLogs, getColor, isBuild, page, testDir } from '~utils'
35

46
test('should have no 404s', () => {
57
browserLogs.forEach((msg) => {
@@ -35,6 +37,10 @@ test('dynamic css', async () => {
3537
await expect.poll(() => getColor('.dynamic')).toBe('red')
3638
})
3739

40+
test('direct dynamic css', async () => {
41+
await expect.poll(() => getColor('.direct-dynamic')).toBe('red')
42+
})
43+
3844
// a CSS-only module shared by multiple chunks becomes a pure CSS chunk that is
3945
// removed from the output. The import map must not keep referencing its removed
4046
// JS file, otherwise chunks importing it 404 and fail to execute
@@ -47,3 +53,75 @@ test('shared pure css chunk', async () => {
4753
test('worker', async () => {
4854
await expect.poll(() => page.textContent('.worker')).toBe('worker: pong')
4955
})
56+
57+
for (const cssFileName of ['dynamic.css', 'direct-dynamic.css']) {
58+
// This is a correctness requirement, not only a cache optimization: hashed
59+
// chunk filenames are cached as immutable. If the filename stayed the same
60+
// while its code changed to reference a new CSS filename, cached JS could
61+
// load stale CSS alongside newly mapped JS, breaking CSS module selectors.
62+
test.runIf(isBuild)(
63+
`${cssFileName} uses a stable import map specifier`,
64+
async () => {
65+
const buildWithColor = async (color: string) =>
66+
(await build({
67+
root: testDir,
68+
logLevel: 'silent',
69+
build: { write: false },
70+
plugins: [
71+
{
72+
name: 'change-dynamic-css',
73+
enforce: 'pre',
74+
transform(code, id) {
75+
if (id.endsWith(`/${cssFileName}`)) {
76+
return code.replace('red', color)
77+
}
78+
},
79+
},
80+
],
81+
})) as RolldownOutput
82+
83+
const getIndexChunk = (output: RolldownOutput) =>
84+
output.output.find(
85+
(file): file is OutputChunk => file.type === 'chunk' && file.isEntry,
86+
)!
87+
const getImportMap = (output: RolldownOutput) =>
88+
JSON.parse(
89+
output.output
90+
.find(
91+
(file): file is OutputAsset => file.fileName === 'importmap.json',
92+
)!
93+
.source.toString(),
94+
).imports as Record<string, string>
95+
const getCssFileName = (output: RolldownOutput) =>
96+
output.output.find(
97+
(file): file is OutputAsset =>
98+
file.type === 'asset' && file.names.includes(cssFileName),
99+
)!.fileName
100+
101+
const redBuild = await buildWithColor('red')
102+
const blueBuild = await buildWithColor('blue')
103+
const redIndex = getIndexChunk(redBuild)
104+
const blueIndex = getIndexChunk(blueBuild)
105+
106+
// The importer chunk does not change
107+
// because the CSS reference uses the hash in the import map
108+
expect(redIndex.fileName).toBe(blueIndex.fileName)
109+
expect(redIndex.code).toBe(blueIndex.code)
110+
111+
const redImportMap = getImportMap(redBuild)
112+
const blueImportMap = getImportMap(blueBuild)
113+
const cssName = cssFileName.slice(0, -'.css'.length)
114+
const cssSpecifier = Object.keys(redImportMap).find(
115+
(specifier) =>
116+
specifier.includes(`/${cssName}-`) && specifier.endsWith('.css'),
117+
)!
118+
119+
// The hash in the import map specifier is stable across builds,
120+
// but the mapped filename changes properly
121+
expect(cssSpecifier).toBeDefined()
122+
expect(redImportMap[cssSpecifier]).toBe(`/${getCssFileName(redBuild)}`)
123+
expect(blueImportMap[cssSpecifier]).toBe(`/${getCssFileName(blueBuild)}`)
124+
expect(redImportMap[cssSpecifier]).not.toBe(blueImportMap[cssSpecifier])
125+
},
126+
)
127+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
.direct-dynamic {
2+
color: red;
3+
}

‎playground/chunk-importmap/index.html‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
<p class="static">static</p>
1414
<p class="dynamic">dynamic</p>
15+
<p class="direct-dynamic">direct dynamic</p>
1516
<p class="shared">shared</p>
1617

1718
<p class="static-js">static-js: error</p>

‎playground/chunk-importmap/index.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import './static.js'
22
import('./dynamic.js')
3+
import('./direct-dynamic.css')
34
import('./dynamic2.js')
45

56
import myWorker from './worker.js?worker'

0 commit comments

Comments
 (0)