Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions packages/vite/src/node/__tests__/build.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,69 @@ describe('build', () => {
assertOutputHashContentChange(result[0], result[1])
})

test('conditional dynamic imports keep both branches preload deps (#23221)', async () => {
const result = (await build({
root: resolve(dirname, 'packages/build-project'),
logLevel: 'silent',
input: 'conditional-import.js',
build: {
write: false,
},
plugins: [
{
name: 'test',
resolveId(id) {
if (
[
'conditional-import.js',
'mobile.js',
'desktop.js',
'mobile.css',
'desktop.css',
].includes(id)
) {
return '\0' + id
}
},
load(id) {
if (id === '\0conditional-import.js') {
return `function load(cond) {
if (cond) { return import('mobile.js') }
else { return import('desktop.js') }
}
window.load = load`
}
if (id === '\0mobile.js') {
return `import 'mobile.css'; export default 'mobile'`
}
if (id === '\0desktop.js') {
return `import 'desktop.css'; export default 'desktop'`
}
if (id === '\0mobile.css') {
return `.mobile { color: red }`
}
if (id === '\0desktop.css') {
return `.desktop { color: blue }`
}
},
},
],
})) as RolldownOutput

const chunk = result.output.find(
(o) => o.type === 'chunk' && o.isEntry,
) as OutputChunk
const registry = /m\.f=(\[[^\]]*\])/.exec(chunk.code)?.[1] ?? '[]'
const deps = registry.match(/"([^"]+)"/g) ?? []

// each branch contributes its JS chunk + its CSS file, so both branches'
// CSS must be present in the preload deps registry (previously one branch's
// deps were silently dropped after minification merged the two
// `__vitePreload` calls).
expect(deps).toHaveLength(4)
expect(deps.filter((dep) => dep.endsWith('.css"'))).toHaveLength(2)
})

test('top-level input is used as the default build entry', async () => {
const result = (await build({
root: resolve(dirname, 'packages/build-project'),
Expand Down
54 changes: 43 additions & 11 deletions packages/vite/src/node/plugins/importAnalysisBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,12 @@ export const preloadMethod = `__vitePreload`
export const preloadMarker = `__VITE_PRELOAD__`

export const preloadHelperId = '\0vite/preload-helper.js'
const preloadMarkerRE = new RegExp(preloadMarker, 'g')
// Matches the plain marker as well as the uniquified markers injected by
// `renderChunk` (`__VITE_PRELOAD_0__`, `__VITE_PRELOAD_1__`, ...). Uniquifying
// the markers keeps the minifier from merging two `__vitePreload` calls from
// mutually-exclusive branches into a single call, which would silently drop one
// branch's preload deps (#23221).
const preloadMarkerRE = /__VITE_PRELOAD(?:_\d*)?__/g

function toRelativePath(filename: string, importer: string) {
const relPath = path.posix.relative(path.posix.dirname(importer), filename)
Expand All @@ -50,6 +55,12 @@ function findPreloadMarker(str: string, pos: number = 0): number {
return result?.index ?? -1
}

function preloadMarkerEnd(str: string, start: number): number {
preloadMarkerRE.lastIndex = start
const result = preloadMarkerRE.exec(str)
return result ? result.index + result[0].length : start
}

/**
* Pairs each dynamic `import()` with the `__VITE_PRELOAD__` marker that belongs to it.
*
Expand Down Expand Up @@ -78,7 +89,7 @@ export function matchImportsToPreloadMarkers(
markerStartPos !== -1;
markerStartPos = findPreloadMarker(
code,
markerStartPos + preloadMarker.length,
preloadMarkerEnd(code, markerStartPos),
)
) {
while (
Expand Down Expand Up @@ -269,18 +280,39 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin[] {
name: 'vite:build-import-analysis',

renderChunk(code, _, { format }) {
const s = new MagicString(code)
if (code.includes(preloadMarker)) {
// Uniquify the `__VITE_PRELOAD__` markers so the minifier does not merge
// two `__vitePreload` calls from mutually-exclusive branches into a
// single call (whose second arg keeps only one branch's deps), silently
// dropping the other branch's preload deps (#23221).
let index = 0
for (let match = preloadMarkerRE.exec(code); match;) {
s.overwrite(
match.index,
match.index + preloadMarker.length,
`__VITE_PRELOAD_${index++}__`,
)
match = preloadMarkerRE.exec(code)
}
}
// make sure we only perform the preload logic in modern builds.
if (code.includes(isModernFlag)) {
const re = new RegExp(isModernFlag, 'g')
const isModern = String(format === 'es')
const isModernWithPadding =
isModern + ' '.repeat(isModernFlag.length - isModern.length)
return {
code: code.replace(re, isModernWithPadding),
map: null,
}
s.replace(re, isModernWithPadding)
}
if (!s.hasChanged()) {
return null
}
return {
code: s.toString(),
map: this.environment.config.build.sourcemap
? s.generateMap({ hires: 'boundary' })
: null,
}
return null
},

async generateBundle(opts, bundle) {
Expand Down Expand Up @@ -378,7 +410,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin[] {
const chunk = bundle[file]
// can't use chunk.dynamicImports.length here since some modules e.g.
// dynamic import to constant json may get inlined.
if (chunk.type === 'chunk' && chunk.code.includes(preloadMarker)) {
if (chunk.type === 'chunk' && findPreloadMarker(chunk.code) >= 0) {
const code = chunk.code
let imports!: ImportSpecifier[]
try {
Expand Down Expand Up @@ -554,7 +586,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin[] {

s.update(
markerStartPos,
markerStartPos + preloadMarker.length,
preloadMarkerEnd(code, markerStartPos),
renderedDeps.length > 0
? `__vite__mapDeps([${renderedDeps.join(',')}])`
: `[]`,
Expand Down Expand Up @@ -588,13 +620,13 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin[] {
if (!rewroteMarkerStartPos.has(markerStartPos)) {
s.update(
markerStartPos,
markerStartPos + preloadMarker.length,
preloadMarkerEnd(code, markerStartPos),
'void 0',
)
}
markerStartPos = findPreloadMarker(
code,
markerStartPos + preloadMarker.length,
preloadMarkerEnd(code, markerStartPos),
)
}

Expand Down
Loading