Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: reduce preload marker markup size #14550

Merged
merged 15 commits into from
Oct 10, 2023
Prev Previous commit
Next Next commit
style: apply prettier
  • Loading branch information
gajus committed Oct 7, 2023
commit fd6f4fd857bcada7a47e0c095d03b0066dfe05cb
88 changes: 52 additions & 36 deletions packages/vite/src/node/plugins/importAnalysisBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ function toRelativePath(filename: string, importer: string) {
function indexOfMatchInSlice(
str: string,
reg: RegExp,
pos: number = 0,
pos: number = 0
): number {
if (pos !== 0) {
str = str.slice(pos)
Expand Down Expand Up @@ -82,7 +82,7 @@ declare const seen: Record<string, boolean>
function preload(
baseModule: () => Promise<{}>,
deps?: string[],
importerUrl?: string,
importerUrl?: string
) {
// @ts-expect-error __VITE_IS_MODERN__ will be replaced with boolean later
if (!__VITE_IS_MODERN__ || !deps || deps.length === 0) {
Expand Down Expand Up @@ -129,11 +129,11 @@ function preload(
return new Promise((res, rej) => {
link.addEventListener('load', res)
link.addEventListener('error', () =>
rej(new Error(`Unable to preload CSS for ${dep}`)),
rej(new Error(`Unable to preload CSS for ${dep}`))
)
})
}
}),
})
)
.then(() => baseModule())
.catch((err) => {
Expand Down Expand Up @@ -230,7 +230,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {

const normalizeUrl = async (
url: string,
pos: number,
pos: number
): Promise<[string, string]> => {
let importerFile = importer

Expand Down Expand Up @@ -262,9 +262,9 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
return this.error(
`Failed to resolve import "${url}" from "${path.relative(
process.cwd(),
importerFile,
importerFile
)}". Does the file exist?`,
pos,
pos
)
}

Expand Down Expand Up @@ -315,7 +315,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
optimizeModulePreloadRelativePaths || customModulePreloadPaths
? ',import.meta.url'
: ''
})`,
})`
)
}

Expand All @@ -341,7 +341,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
depsOptimizer.metadata,
file,
config,
ssr,
ssr
)

let rewriteDone = false
Expand All @@ -353,8 +353,8 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
if (!file.match(optimizedDepDynamicRE)) {
config.logger.error(
colors.red(
`Vite Error, ${url} optimized info should be defined`,
),
`Vite Error, ${url} optimized info should be defined`
)
)
}
} else if (needsInterop) {
Expand All @@ -365,7 +365,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
url,
index,
importer,
config,
config
)
rewriteDone = true
}
Expand Down Expand Up @@ -453,19 +453,22 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
type FileDep = {
url: string
runtime: boolean
};
}

const fileDeps: FileDep[] = []
const addFileDep = (url: string, runtime: boolean = false): number => {
const addFileDep = (
url: string,
runtime: boolean = false
): number => {
const index = fileDeps.findIndex((dep) => dep.url === url)
if (index === -1) {
return fileDeps.push({url, runtime}) - 1
return fileDeps.push({ url, runtime }) - 1
} else {
return index
}
}
const getFileDep = (index: number): FileDep => {
const fileDep = fileDeps[index];
const fileDep = fileDeps[index]
if (!fileDep) {
throw new Error(`Cannot find file dep at index ${index}`)
}
Expand Down Expand Up @@ -497,7 +500,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
if (url) {
normalizedFile = path.posix.join(
path.posix.dirname(chunk.fileName),
url,
url
)

const ownerFilename = chunk.fileName
Expand Down Expand Up @@ -538,13 +541,13 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
let markerStartPos = indexOfMatchInSlice(
code,
preloadMarkerWithQuote,
end,
end
)
// fix issue #3051
if (markerStartPos === -1 && imports.length === 1) {
markerStartPos = indexOfMatchInSlice(
code,
preloadMarkerWithQuote,
preloadMarkerWithQuote
)
}

Expand All @@ -557,7 +560,9 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
? modulePreload === false
? // CSS deps use the same mechanism as module preloads, so even if disabled,
// we still need to pass these deps to the preload helper in dynamic imports.
[...deps].filter((d) => getFileDep(d).url.endsWith('.css'))
[...deps].filter((d) =>
getFileDep(d).url.endsWith('.css')
)
: [...deps]
: []

Expand All @@ -574,13 +579,20 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
const cssDeps: number[] = []
const otherDeps: number[] = []
for (const dep of depsArray) {
;(getFileDep(dep).url.endsWith('.css') ? cssDeps : otherDeps).push(dep)
;(getFileDep(dep).url.endsWith('.css')
gajus marked this conversation as resolved.
Show resolved Hide resolved
? cssDeps
: otherDeps
).push(dep)
}
resolvedDeps = [
...resolveDependencies(normalizedFile, otherDeps.map((otherDep) => getFileDep(otherDep).url), {
hostId: file,
hostType: 'js',
}).map((otherDep) => addFileDep(otherDep)),
...resolveDependencies(
normalizedFile,
otherDeps.map((otherDep) => getFileDep(otherDep).url),
{
hostId: file,
hostType: 'js',
}
).map((otherDep) => addFileDep(otherDep)),
gajus marked this conversation as resolved.
Show resolved Hide resolved
...cssDeps,
]
} else {
Expand All @@ -594,36 +606,40 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
chunk.fileName,
'js',
config,
toRelativePath,
toRelativePath
)

if (typeof replacement === 'string') {
return addFileDep(replacement);
return addFileDep(replacement)
}

return addFileDep(replacement.runtime, true);
return addFileDep(replacement.runtime, true)
})
} else {
renderedDeps = depsArray.map((d) =>
// Don't include the assets dir if the default asset file names
// are used, the path will be reconstructed by the import preload helper
optimizeModulePreloadRelativePaths
? addFileDep(toRelativePath(getFileDep(d).url, file))
: d,
optimizeModulePreloadRelativePaths
? addFileDep(toRelativePath(getFileDep(d).url, file))
: d
)
}

s.update(
markerStartPos,
markerStartPos + preloadMarker.length + 2,
`__viteMapDep([${renderedDeps.join(',')}])`,
`__viteMapDep([${renderedDeps.join(',')}])`
)
rewroteMarkerStartPos.add(markerStartPos)
}
}
}

const fileDepsCode = `[${fileDeps.map((fileDep) => fileDep.runtime ? fileDep.url : JSON.stringify(fileDep.url)).join(',')}]`;
const fileDepsCode = `[${fileDeps
.map((fileDep) =>
fileDep.runtime ? fileDep.url : JSON.stringify(fileDep.url)
)
.join(',')}]`

s.append(`\
function __viteMapDep(indexes) {
gajus marked this conversation as resolved.
Show resolved Hide resolved
Expand All @@ -641,13 +657,13 @@ function __viteMapDep(indexes) {
s.update(
markerStartPos,
markerStartPos + preloadMarker.length + 2,
'void 0',
'void 0'
)
}
markerStartPos = indexOfMatchInSlice(
code,
preloadMarkerWithQuote,
markerStartPos + preloadMarker.length + 2,
markerStartPos + preloadMarker.length + 2
)
}

Expand All @@ -668,7 +684,7 @@ function __viteMapDep(indexes) {
if (config.build.sourcemap === 'inline') {
chunk.code = chunk.code.replace(
convertSourceMap.mapFileCommentRegex,
'',
''
)
chunk.code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`
} else if (config.build.sourcemap) {
Expand Down