fix(vite): optimise layer dependencies with vite (#25752)

This commit is contained in:
Daniel Roe 2024-02-13 09:54:13 +00:00 committed by GitHub
parent 795050e68c
commit f0a7ccd588
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,6 +1,6 @@
import { existsSync } from 'node:fs'
import * as vite from 'vite'
import { dirname, join, resolve } from 'pathe'
import { dirname, join, normalize, resolve } from 'pathe'
import type { Nuxt, NuxtBuilder, ViteConfig } from '@nuxt/schema'
import { addVitePlugin, isIgnored, logger, resolvePath } from '@nuxt/kit'
import replace from '@rollup/plugin-replace'
@ -138,6 +138,31 @@ export const bundle: NuxtBuilder['bundle'] = async (nuxt) => {
ctx.config.build!.watch = undefined
}
if (nuxt.options.dev) {
// Identify which layers will need to have an extra resolve step.
const layerDirs: string[] = []
const delimitedRootDir = nuxt.options.rootDir + '/'
for (const layer of nuxt.options._layers) {
if (layer.config.srcDir !== nuxt.options.srcDir && !layer.config.srcDir.startsWith(delimitedRootDir)) {
layerDirs.push(layer.config.srcDir + '/')
}
}
if (layerDirs.length > 0) {
ctx.config.plugins!.push({
name: 'nuxt:optimize-layer-deps',
enforce: 'pre',
async resolveId (source, _importer) {
if (!_importer) { return }
const importer = normalize(_importer)
if (layerDirs.some(dir => importer.startsWith(dir))) {
// 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)
}
},
})
}
}
// Add type-checking
if (!ctx.nuxt.options.test && (ctx.nuxt.options.typescript.typeCheck === true || (ctx.nuxt.options.typescript.typeCheck === 'build' && !ctx.nuxt.options.dev))) {
const checker = await import('vite-plugin-checker').then(r => r.default)