perf(vite): avoid extra resolve call for resolveId in layers (#27971)

This commit is contained in:
Daniel Roe 2024-07-02 19:26:58 +01:00
parent 90900c6c8a
commit 20dc6e5030
No known key found for this signature in database
GPG Key ID: CBC814C393D93268

View File

@ -124,6 +124,7 @@ export const bundle: NuxtBuilder['bundle'] = async (nuxt) => {
ctx.config.build!.watch = undefined ctx.config.build!.watch = undefined
} }
// TODO: this may no longer be needed with most recent vite version
if (nuxt.options.dev) { if (nuxt.options.dev) {
// Identify which layers will need to have an extra resolve step. // Identify which layers will need to have an extra resolve step.
const layerDirs: string[] = [] const layerDirs: string[] = []
@ -134,17 +135,24 @@ export const bundle: NuxtBuilder['bundle'] = async (nuxt) => {
} }
} }
if (layerDirs.length > 0) { if (layerDirs.length > 0) {
ctx.config.plugins!.push({ // Reverse so longest/most specific directories are searched first
name: 'nuxt:optimize-layer-deps', layerDirs.sort().reverse()
enforce: 'pre', ctx.nuxt.hook('vite:extendConfig', (config) => {
async resolveId (source, _importer) { const dirs = [...layerDirs]
if (!_importer) { return } config.plugins!.push({
const importer = normalize(_importer) name: 'nuxt:optimize-layer-deps',
if (layerDirs.some(dir => importer.startsWith(dir))) { enforce: 'pre',
async resolveId (source, _importer) {
if (!_importer || !dirs.length) { return }
const importer = normalize(_importer)
const layerIndex = dirs.findIndex(dir => importer.startsWith(dir))
// Trigger vite to optimize dependencies imported within a layer, just as if they were imported in final project // Trigger vite to optimize dependencies imported within a layer, just as if they were imported in final project
await this.resolve(source, join(nuxt.options.srcDir, 'index.html'), { skipSelf: true }).catch(() => null) if (layerIndex !== -1) {
} dirs.splice(layerIndex, 1)
}, await this.resolve(source, join(nuxt.options.srcDir, 'index.html'), { skipSelf: true }).catch(() => null)
}
},
})
}) })
} }
} }