Skip to content

Commit

Permalink
fix(importAnalysisBuild): support parsing '__VITE_PRELOAD__' (#13023)
Browse files Browse the repository at this point in the history
  • Loading branch information
sun0day authored Apr 28, 2023
1 parent fe73198 commit 447df7c
Showing 1 changed file with 30 additions and 9 deletions.
39 changes: 30 additions & 9 deletions packages/vite/src/node/plugins/importAnalysisBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const preloadMarker = `__VITE_PRELOAD__`
export const preloadBaseMarker = `__VITE_PRELOAD_BASE__`

export const preloadHelperId = '\0vite/preload-helper'
const preloadMarkerWithQuote = `"${preloadMarker}"` as const
const preloadMarkerWithQuote = new RegExp(`['"]${preloadMarker}['"]`)

const dynamicImportPrefixRE = /import\s*\(/

Expand All @@ -49,6 +49,20 @@ function toRelativePath(filename: string, importer: string) {
return relPath[0] === '.' ? relPath : `./${relPath}`
}

function indexOfMatchInSlice(
str: string,
reg: RegExp,
pos: number = 0,
): number {
if (pos !== 0) {
str = str.slice(pos)
}

const matcher = str.match(reg)

return matcher?.index !== undefined ? matcher.index + pos : -1
}

/**
* Helper for preloading CSS and direct imports of async chunks in parallel to
* the async chunk itself.
Expand Down Expand Up @@ -507,10 +521,17 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
addDeps(normalizedFile)
}

let markerStartPos = code.indexOf(preloadMarkerWithQuote, end)
let markerStartPos = indexOfMatchInSlice(
code,
preloadMarkerWithQuote,
end,
)
// fix issue #3051
if (markerStartPos === -1 && imports.length === 1) {
markerStartPos = code.indexOf(preloadMarkerWithQuote)
markerStartPos = indexOfMatchInSlice(
code,
preloadMarkerWithQuote,
)
}

if (markerStartPos > 0) {
Expand Down Expand Up @@ -577,7 +598,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {

s.update(
markerStartPos,
markerStartPos + preloadMarkerWithQuote.length,
markerStartPos + preloadMarker.length + 2,
`[${renderedDeps.join(',')}]`,
)
rewroteMarkerStartPos.add(markerStartPos)
Expand All @@ -587,19 +608,19 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {

// there may still be markers due to inlined dynamic imports, remove
// all the markers regardless
let markerStartPos = code.indexOf(preloadMarkerWithQuote)
let markerStartPos = indexOfMatchInSlice(code, preloadMarkerWithQuote)
while (markerStartPos >= 0) {
if (!rewroteMarkerStartPos.has(markerStartPos)) {
s.update(
markerStartPos,
markerStartPos + preloadMarkerWithQuote.length,
markerStartPos + preloadMarker.length + 2,
'void 0',
)
}

markerStartPos = code.indexOf(
markerStartPos = indexOfMatchInSlice(
code,
preloadMarkerWithQuote,
markerStartPos + preloadMarkerWithQuote.length,
markerStartPos + preloadMarker.length + 2,
)
}

Expand Down

0 comments on commit 447df7c

Please sign in to comment.