Skip to content

Commit

Permalink
fix(preload): skip preload for non-static urls (#16556)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy authored Apr 30, 2024
1 parent 8c6d4be commit bb79c9b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
10 changes: 9 additions & 1 deletion packages/vite/src/node/plugins/importAnalysisBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {

for (let index = 0; index < imports.length; index++) {
const {
s: start,
e: end,
ss: expStart,
se: expEnd,
Expand All @@ -255,7 +256,14 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
str().remove(end + 1, expEnd)
}

if (isDynamicImport && insertPreload) {
if (
isDynamicImport &&
insertPreload &&
// Only preload static urls
(source[start] === '"' ||
source[start] === "'" ||
source[start] === '`')
) {
needPreloadHelper = true
str().prependLeft(expStart, `${preloadMethod}(() => `)
str().appendRight(
Expand Down
15 changes: 14 additions & 1 deletion playground/dynamic-import/__tests__/dynamic-import.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { expect, test } from 'vitest'
import { getColor, isBuild, page, serverLogs, untilUpdated } from '~utils'
import {
findAssetFile,
getColor,
isBuild,
page,
serverLogs,
untilUpdated,
} from '~utils'

test('should load literal dynamic import', async () => {
await page.click('.baz')
Expand Down Expand Up @@ -170,3 +177,9 @@ test.runIf(isBuild)(
)
},
)

test.runIf(isBuild)('should not preload for non-analyzable urls', () => {
const js = findAssetFile(/index-[-\w]{8}\.js$/)
// should match e.g. await import(e.jss);o(".view",p===i)
expect(js).to.match(/\.jss\);/)
})

0 comments on commit bb79c9b

Please sign in to comment.