refactor(nuxt,schema,vite,webpack): use unplugin for vfs (#29165)

This commit is contained in:
Daniel Roe 2024-10-09 14:58:05 +02:00 committed by GitHub
parent e95edac5d9
commit 56d2261471
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
30 changed files with 159 additions and 149 deletions

View File

@ -223,13 +223,10 @@ export async function _generateTypes (nuxt: Nuxt) {
exclude: [...exclude], exclude: [...exclude],
} satisfies TSConfig) } satisfies TSConfig)
const aliases: Record<string, string> = { const aliases: Record<string, string> = nuxt.options.alias
...nuxt.options.alias,
'#build': nuxt.options.buildDir,
}
// Exclude bridge alias types to support Volar // Exclude bridge alias types to support Volar
const excludedAlias = [/^@vue\/.*$/] const excludedAlias = [/^@vue\/.*$/, /^#internal\/nuxt/]
const basePath = tsConfig.compilerOptions!.baseUrl const basePath = tsConfig.compilerOptions!.baseUrl
? resolve(nuxt.options.buildDir, tsConfig.compilerOptions!.baseUrl) ? resolve(nuxt.options.buildDir, tsConfig.compilerOptions!.baseUrl)

View File

@ -34,9 +34,6 @@ describe('tsConfig generation', () => {
const { tsConfig } = await _generateTypes(mockNuxt) const { tsConfig } = await _generateTypes(mockNuxt)
expect(tsConfig.compilerOptions?.paths).toMatchInlineSnapshot(` expect(tsConfig.compilerOptions?.paths).toMatchInlineSnapshot(`
{ {
"#build": [
".",
],
"some-custom-alias": [ "some-custom-alias": [
"../some-alias", "../some-alias",
], ],

View File

@ -1,6 +1,6 @@
import { existsSync, statSync, writeFileSync } from 'node:fs' import { existsSync, statSync, writeFileSync } from 'node:fs'
import { isAbsolute, join, normalize, relative, resolve } from 'pathe' import { isAbsolute, join, normalize, relative, resolve } from 'pathe'
import { addBuildPlugin, addPluginTemplate, addTemplate, addTypeTemplate, addVitePlugin, defineNuxtModule, logger, resolveAlias, resolvePath, updateTemplates } from '@nuxt/kit' import { addBuildPlugin, addPluginTemplate, addTemplate, addTypeTemplate, addVitePlugin, defineNuxtModule, findPath, logger, resolveAlias, resolvePath, updateTemplates } from '@nuxt/kit'
import type { Component, ComponentsDir, ComponentsOptions } from 'nuxt/schema' import type { Component, ComponentsDir, ComponentsOptions } from 'nuxt/schema'
import { distDir } from '../dirs' import { distDir } from '../dirs'
@ -32,7 +32,7 @@ export default defineNuxtModule<ComponentsOptions>({
defaults: { defaults: {
dirs: [], dirs: [],
}, },
setup (componentOptions, nuxt) { async setup (componentOptions, nuxt) {
let componentDirs: ComponentsDir[] = [] let componentDirs: ComponentsDir[] = []
const context = { const context = {
components: [] as Component[], components: [] as Component[],
@ -134,8 +134,9 @@ export default defineNuxtModule<ComponentsOptions>({
addTemplate(componentsMetadataTemplate) addTemplate(componentsMetadataTemplate)
} }
addBuildPlugin(TransformPlugin(nuxt, getComponents, 'server'), { server: true, client: false }) const serverComponentRuntime = await findPath(join(distDir, 'components/runtime/server-component')) ?? join(distDir, 'components/runtime/server-component')
addBuildPlugin(TransformPlugin(nuxt, getComponents, 'client'), { server: false, client: true }) addBuildPlugin(TransformPlugin(nuxt, { getComponents, serverComponentRuntime, mode: 'server' }), { server: true, client: false })
addBuildPlugin(TransformPlugin(nuxt, { getComponents, serverComponentRuntime, mode: 'client' }), { server: false, client: true })
// Do not prefetch global components chunks // Do not prefetch global components chunks
nuxt.hook('build:manifest', (manifest) => { nuxt.hook('build:manifest', (manifest) => {
@ -162,7 +163,7 @@ export default defineNuxtModule<ComponentsOptions>({
} }
}) })
const serverPlaceholderPath = resolve(distDir, 'app/components/server-placeholder') const serverPlaceholderPath = await findPath(join(distDir, 'app/components/server-placeholder')) ?? join(distDir, 'app/components/server-placeholder')
// Scan components and add to plugin // Scan components and add to plugin
nuxt.hook('app:templates', async (app) => { nuxt.hook('app:templates', async (app) => {
@ -222,6 +223,7 @@ export default defineNuxtModule<ComponentsOptions>({
const sharedLoaderOptions = { const sharedLoaderOptions = {
getComponents, getComponents,
serverComponentRuntime,
transform: typeof nuxt.options.components === 'object' && !Array.isArray(nuxt.options.components) ? nuxt.options.components.transform : undefined, transform: typeof nuxt.options.components === 'object' && !Array.isArray(nuxt.options.components) ? nuxt.options.components.transform : undefined,
experimentalComponentIslands: !!nuxt.options.experimental.componentIslands, experimentalComponentIslands: !!nuxt.options.experimental.componentIslands,
} }

View File

@ -2,16 +2,16 @@ import { createUnplugin } from 'unplugin'
import { genDynamicImport, genImport } from 'knitwork' import { genDynamicImport, genImport } from 'knitwork'
import MagicString from 'magic-string' import MagicString from 'magic-string'
import { pascalCase } from 'scule' import { pascalCase } from 'scule'
import { relative, resolve } from 'pathe' import { relative } from 'pathe'
import type { Component, ComponentsOptions } from 'nuxt/schema' import type { Component, ComponentsOptions } from 'nuxt/schema'
import { logger, tryUseNuxt } from '@nuxt/kit' import { logger, tryUseNuxt } from '@nuxt/kit'
import { distDir } from '../../dirs'
import { isVue } from '../../core/utils' import { isVue } from '../../core/utils'
interface LoaderOptions { interface LoaderOptions {
getComponents (): Component[] getComponents (): Component[]
mode: 'server' | 'client' mode: 'server' | 'client'
serverComponentRuntime: string
sourcemap?: boolean sourcemap?: boolean
transform?: ComponentsOptions['transform'] transform?: ComponentsOptions['transform']
experimentalComponentIslands?: boolean experimentalComponentIslands?: boolean
@ -20,7 +20,6 @@ interface LoaderOptions {
export const LoaderPlugin = (options: LoaderOptions) => createUnplugin(() => { export const LoaderPlugin = (options: LoaderOptions) => createUnplugin(() => {
const exclude = options.transform?.exclude || [] const exclude = options.transform?.exclude || []
const include = options.transform?.include || [] const include = options.transform?.include || []
const serverComponentRuntime = resolve(distDir, 'components/runtime/server-component')
const nuxt = tryUseNuxt() const nuxt = tryUseNuxt()
return { return {
@ -62,7 +61,7 @@ export const LoaderPlugin = (options: LoaderOptions) => createUnplugin(() => {
const isServerOnly = !component._raw && component.mode === 'server' && const isServerOnly = !component._raw && component.mode === 'server' &&
!components.some(c => c.pascalName === component.pascalName && c.mode === 'client') !components.some(c => c.pascalName === component.pascalName && c.mode === 'client')
if (isServerOnly) { if (isServerOnly) {
imports.add(genImport(serverComponentRuntime, [{ name: 'createServerComponent' }])) imports.add(genImport(options.serverComponentRuntime, [{ name: 'createServerComponent' }]))
imports.add(`const ${identifier} = createServerComponent(${JSON.stringify(component.pascalName)})`) imports.add(`const ${identifier} = createServerComponent(${JSON.stringify(component.pascalName)})`)
if (!options.experimentalComponentIslands) { if (!options.experimentalComponentIslands) {
logger.warn(`Standalone server components (\`${name}\`) are not yet supported without enabling \`experimental.componentIslands\`.`) logger.warn(`Standalone server components (\`${name}\`) are not yet supported without enabling \`experimental.componentIslands\`.`)

View File

@ -5,15 +5,19 @@ import { createUnimport } from 'unimport'
import { createUnplugin } from 'unplugin' import { createUnplugin } from 'unplugin'
import { parseURL } from 'ufo' import { parseURL } from 'ufo'
import { parseQuery } from 'vue-router' import { parseQuery } from 'vue-router'
import { normalize, resolve } from 'pathe' import { normalize } from 'pathe'
import { genImport } from 'knitwork' import { genImport } from 'knitwork'
import { distDir } from '../../dirs'
import type { getComponentsT } from '../module' import type { getComponentsT } from '../module'
const COMPONENT_QUERY_RE = /[?&]nuxt_component=/ const COMPONENT_QUERY_RE = /[?&]nuxt_component=/
export function TransformPlugin (nuxt: Nuxt, getComponents: getComponentsT, mode: 'client' | 'server' | 'all') { interface TransformPluginOptions {
const serverComponentRuntime = resolve(distDir, 'components/runtime/server-component') getComponents: getComponentsT
mode: 'client' | 'server' | 'all'
serverComponentRuntime: string
}
export function TransformPlugin (nuxt: Nuxt, options: TransformPluginOptions) {
const componentUnimport = createUnimport({ const componentUnimport = createUnimport({
imports: [ imports: [
{ {
@ -26,7 +30,7 @@ export function TransformPlugin (nuxt: Nuxt, getComponents: getComponentsT, mode
}) })
function getComponentsImports (): Import[] { function getComponentsImports (): Import[] {
const components = getComponents(mode) const components = options.getComponents(options.mode)
return components.flatMap((c): Import[] => { return components.flatMap((c): Import[] => {
const withMode = (mode: string | undefined) => mode const withMode = (mode: string | undefined) => mode
? `${c.filePath}${c.filePath.includes('?') ? '&' : '?'}nuxt_component=${mode}&nuxt_component_name=${c.pascalName}&nuxt_component_export=${c.export || 'default'}` ? `${c.filePath}${c.filePath.includes('?') ? '&' : '?'}nuxt_component=${mode}&nuxt_component_name=${c.pascalName}&nuxt_component_export=${c.export || 'default'}`
@ -95,7 +99,7 @@ export function TransformPlugin (nuxt: Nuxt, getComponents: getComponentsT, mode
const name = query.nuxt_component_name const name = query.nuxt_component_name
return { return {
code: [ code: [
`import { createServerComponent } from ${JSON.stringify(serverComponentRuntime)}`, `import { createServerComponent } from ${JSON.stringify(options.serverComponentRuntime)}`,
`${exportWording} createServerComponent(${JSON.stringify(name)})`, `${exportWording} createServerComponent(${JSON.stringify(name)})`,
].join('\n'), ].join('\n'),
map: null, map: null,

View File

@ -33,8 +33,9 @@ export const TreeShakeTemplatePlugin = (options: TreeShakeTemplatePluginOptions)
const components = options.getComponents() const components = options.getComponents()
if (!regexpMap.has(components)) { if (!regexpMap.has(components)) {
const serverPlaceholderPath = resolve(distDir, 'app/components/server-placeholder')
const clientOnlyComponents = components const clientOnlyComponents = components
.filter(c => c.mode === 'client' && !components.some(other => other.mode !== 'client' && other.pascalName === c.pascalName && other.filePath !== resolve(distDir, 'app/components/server-placeholder'))) .filter(c => c.mode === 'client' && !components.some(other => other.mode !== 'client' && other.pascalName === c.pascalName && !other.filePath.startsWith(serverPlaceholderPath)))
.flatMap(c => [c.pascalName, c.kebabName.replaceAll('-', '_')]) .flatMap(c => [c.pascalName, c.kebabName.replaceAll('-', '_')])
.concat(['ClientOnly', 'client_only']) .concat(['ClientOnly', 'client_only'])

View File

@ -72,7 +72,7 @@ export async function generateApp (nuxt: Nuxt, app: NuxtApp, options: { filter?:
if (template.modified) { if (template.modified) {
nuxt.vfs[fullPath] = contents nuxt.vfs[fullPath] = contents
const aliasPath = '#build/' + template.filename!.replace(/\.\w+$/, '') const aliasPath = '#build/' + template.filename
nuxt.vfs[aliasPath] = contents nuxt.vfs[aliasPath] = contents
// In case a non-normalized absolute path is called for on Windows // In case a non-normalized absolute path is called for on Windows

View File

@ -101,8 +101,8 @@ export async function initNitro (nuxt: Nuxt & { _nitro?: Nitro }) {
devHandlers: [], devHandlers: [],
baseURL: nuxt.options.app.baseURL, baseURL: nuxt.options.app.baseURL,
virtual: { virtual: {
'#internal/nuxt.config.mjs': () => nuxt.vfs['#build/nuxt.config'], '#internal/nuxt.config.mjs': () => nuxt.vfs['#build/nuxt.config.mjs'],
'#internal/nuxt/app-config': () => nuxt.vfs['#build/app.config']?.replace(/\/\*\* client \*\*\/[\s\S]*\/\*\* client-end \*\*\//, ''), '#internal/nuxt/app-config': () => nuxt.vfs['#build/app.config.mjs']?.replace(/\/\*\* client \*\*\/[\s\S]*\/\*\* client-end \*\*\//, ''),
'#spa-template': async () => `export const template = ${JSON.stringify(await spaLoadingTemplate(nuxt))}`, '#spa-template': async () => `export const template = ${JSON.stringify(await spaLoadingTemplate(nuxt))}`,
}, },
routeRules: { routeRules: {
@ -189,11 +189,11 @@ export async function initNitro (nuxt: Nuxt & { _nitro?: Nitro }) {
}, },
'@vue/devtools-api': 'vue-devtools-stub', '@vue/devtools-api': 'vue-devtools-stub',
// Paths
'#internal/nuxt/paths': resolve(distDir, 'core/runtime/nitro/paths'),
// Nuxt aliases // Nuxt aliases
...nuxt.options.alias, ...nuxt.options.alias,
// Paths
'#internal/nuxt/paths': resolve(distDir, 'core/runtime/nitro/paths'),
}, },
replace: { replace: {
'process.env.NUXT_NO_SSR': nuxt.options.ssr === false, 'process.env.NUXT_NO_SSR': nuxt.options.ssr === false,

View File

@ -44,6 +44,7 @@ import { RemovePluginMetadataPlugin } from './plugins/plugin-metadata'
import { AsyncContextInjectionPlugin } from './plugins/async-context' import { AsyncContextInjectionPlugin } from './plugins/async-context'
import { resolveDeepImportsPlugin } from './plugins/resolve-deep-imports' import { resolveDeepImportsPlugin } from './plugins/resolve-deep-imports'
import { prehydrateTransformPlugin } from './plugins/prehydrate' import { prehydrateTransformPlugin } from './plugins/prehydrate'
import { VirtualFSPlugin } from './plugins/virtual'
export function createNuxt (options: NuxtOptions): Nuxt { export function createNuxt (options: NuxtOptions): Nuxt {
const hooks = createHooks<NuxtHooks>() const hooks = createHooks<NuxtHooks>()
@ -240,6 +241,10 @@ async function initNuxt (nuxt: Nuxt) {
} }
} }
// Support Nuxt VFS
addBuildPlugin(VirtualFSPlugin(nuxt, { mode: 'server' }), { client: false })
addBuildPlugin(VirtualFSPlugin(nuxt, { mode: 'client', alias: { 'nitro/runtime': join(nuxt.options.buildDir, 'nitro.client.mjs') } }), { server: false })
// Add plugin normalization plugin // Add plugin normalization plugin
addBuildPlugin(RemovePluginMetadataPlugin(nuxt)) addBuildPlugin(RemovePluginMetadataPlugin(nuxt))

View File

@ -16,7 +16,7 @@ export function resolveDeepImportsPlugin (nuxt: Nuxt): Plugin {
conditions = config.mode === 'test' ? [...config.resolve.conditions, 'import', 'require'] : config.resolve.conditions conditions = config.mode === 'test' ? [...config.resolve.conditions, 'import', 'require'] : config.resolve.conditions
}, },
async resolveId (id, importer) { async resolveId (id, importer) {
if (!importer || isAbsolute(id) || (!isAbsolute(importer) && !importer.startsWith('virtual:')) || exclude.some(e => id.startsWith(e))) { if (!importer || isAbsolute(id) || (!isAbsolute(importer) && !importer.startsWith('virtual:') && !importer.startsWith('\0virtual:')) || exclude.some(e => id.startsWith(e))) {
return return
} }

View File

@ -0,0 +1,67 @@
import { resolveAlias } from '@nuxt/kit'
import type { Nuxt } from '@nuxt/schema'
import { dirname, isAbsolute, resolve } from 'pathe'
import { createUnplugin } from 'unplugin'
const PREFIX = '\0virtual:nuxt:'
interface VirtualFSPluginOptions {
mode: 'client' | 'server'
alias?: Record<string, string>
}
export const VirtualFSPlugin = (nuxt: Nuxt, options: VirtualFSPluginOptions) => createUnplugin(() => {
const extensions = ['', ...nuxt.options.extensions]
const alias = { ...nuxt.options.alias, ...options.alias }
const resolveWithExt = (id: string) => {
for (const suffix of ['', '.' + options.mode]) {
for (const ext of extensions) {
const rId = id + suffix + ext
if (rId in nuxt.vfs) {
return rId
}
}
}
}
return {
name: 'nuxt:virtual',
resolveId (id, importer) {
id = resolveAlias(id, alias)
if (process.platform === 'win32' && isAbsolute(id)) {
// Add back C: prefix on Windows
id = resolve(id)
}
const resolvedId = resolveWithExt(id)
if (resolvedId) {
return PREFIX + resolvedId
}
if (importer && /^\.{1,2}[\\/]/.test(id)) {
const path = resolve(dirname(withoutPrefix(importer)), id)
const resolved = resolveWithExt(path)
if (resolved) {
return PREFIX + resolved
}
}
},
loadInclude (id) {
return id.startsWith(PREFIX) && withoutPrefix(id) in nuxt.vfs
},
load (id) {
return {
code: nuxt.vfs[withoutPrefix(id)] || '',
map: null,
}
},
}
})
function withoutPrefix (id: string) {
return id.startsWith(PREFIX) ? id.slice(PREFIX.length) : id
}

View File

@ -58,7 +58,7 @@ export const cssTemplate: NuxtTemplate = {
} }
export const clientPluginTemplate: NuxtTemplate = { export const clientPluginTemplate: NuxtTemplate = {
filename: 'plugins/client.mjs', filename: 'plugins.client.mjs',
async getContents (ctx) { async getContents (ctx) {
const clientPlugins = await annotatePlugins(ctx.nuxt, ctx.app.plugins.filter(p => !p.mode || p.mode !== 'server')) const clientPlugins = await annotatePlugins(ctx.nuxt, ctx.app.plugins.filter(p => !p.mode || p.mode !== 'server'))
checkForCircularDependencies(clientPlugins) checkForCircularDependencies(clientPlugins)
@ -78,7 +78,7 @@ export const clientPluginTemplate: NuxtTemplate = {
} }
export const serverPluginTemplate: NuxtTemplate = { export const serverPluginTemplate: NuxtTemplate = {
filename: 'plugins/server.mjs', filename: 'plugins.server.mjs',
async getContents (ctx) { async getContents (ctx) {
const serverPlugins = await annotatePlugins(ctx.nuxt, ctx.app.plugins.filter(p => !p.mode || p.mode !== 'client')) const serverPlugins = await annotatePlugins(ctx.nuxt, ctx.app.plugins.filter(p => !p.mode || p.mode !== 'client'))
checkForCircularDependencies(serverPlugins) checkForCircularDependencies(serverPlugins)

View File

@ -76,8 +76,8 @@ export default import.meta.server ? [CapoPlugin({ track: true })] : [];`
// template is only exposed in nuxt context, expose in nitro context as well // template is only exposed in nuxt context, expose in nitro context as well
nuxt.hooks.hook('nitro:config', (config) => { nuxt.hooks.hook('nitro:config', (config) => {
config.virtual!['#internal/unhead-plugins.mjs'] = () => nuxt.vfs['#build/unhead-plugins'] config.virtual!['#internal/unhead-plugins.mjs'] = () => nuxt.vfs['#build/unhead-plugins.mjs']
config.virtual!['#internal/unhead.config.mjs'] = () => nuxt.vfs['#build/unhead.config'] config.virtual!['#internal/unhead.config.mjs'] = () => nuxt.vfs['#build/unhead.config.mjs']
}) })
// Add library-specific plugin // Add library-specific plugin

View File

@ -52,7 +52,7 @@ export default defineNuxtModule({
} }
// Add default options at beginning // Add default options at beginning
context.files.unshift({ path: resolve(runtimeDir, 'router.options'), optional: true }) context.files.unshift({ path: await findPath(resolve(runtimeDir, 'router.options')) || resolve(runtimeDir, 'router.options'), optional: true })
await nuxt.callHook('pages:routerOptions', context) await nuxt.callHook('pages:routerOptions', context)
return context.files return context.files
@ -487,12 +487,19 @@ export default defineNuxtModule({
} }
}) })
const serverComponentRuntime = await findPath(join(distDir, 'components/runtime/server-component')) ?? join(distDir, 'components/runtime/server-component')
const clientComponentRuntime = await findPath(join(distDir, 'components/runtime/client-component')) ?? join(distDir, 'components/runtime/client-component')
// Add routes template // Add routes template
addTemplate({ addTemplate({
filename: 'routes.mjs', filename: 'routes.mjs',
getContents ({ app }) { getContents ({ app }) {
if (!app.pages) { return 'export default []' } if (!app.pages) { return 'export default []' }
const { routes, imports } = normalizeRoutes(app.pages, new Set(), nuxt.options.experimental.scanPageMeta) const { routes, imports } = normalizeRoutes(app.pages, new Set(), {
serverComponentRuntime,
clientComponentRuntime,
overrideMeta: nuxt.options.experimental.scanPageMeta,
})
return [...imports, `export default ${routes}`].join('\n') return [...imports, `export default ${routes}`].join('\n')
}, },
}) })

View File

@ -15,7 +15,6 @@ import type { NuxtPage } from 'nuxt/schema'
import { getLoader, uniqueBy } from '../core/utils' import { getLoader, uniqueBy } from '../core/utils'
import { toArray } from '../utils' import { toArray } from '../utils'
import { distDir } from '../dirs'
enum SegmentParserState { enum SegmentParserState {
initial, initial,
@ -476,7 +475,12 @@ function serializeRouteValue (value: any, skipSerialisation = false) {
type NormalizedRoute = Partial<Record<Exclude<keyof NuxtPage, 'file'>, string>> & { component?: string } type NormalizedRoute = Partial<Record<Exclude<keyof NuxtPage, 'file'>, string>> & { component?: string }
type NormalizedRouteKeys = (keyof NormalizedRoute)[] type NormalizedRouteKeys = (keyof NormalizedRoute)[]
export function normalizeRoutes (routes: NuxtPage[], metaImports: Set<string> = new Set(), overrideMeta = false): { imports: Set<string>, routes: string } { interface NormalizeRoutesOptions {
overrideMeta?: boolean
serverComponentRuntime: string
clientComponentRuntime: string
}
export function normalizeRoutes (routes: NuxtPage[], metaImports: Set<string> = new Set(), options: NormalizeRoutesOptions): { imports: Set<string>, routes: string } {
return { return {
imports: metaImports, imports: metaImports,
routes: genArrayFromRaw(routes.map((page) => { routes: genArrayFromRaw(routes.map((page) => {
@ -506,7 +510,7 @@ export function normalizeRoutes (routes: NuxtPage[], metaImports: Set<string> =
} }
if (page.children?.length) { if (page.children?.length) {
route.children = normalizeRoutes(page.children, metaImports, overrideMeta).routes route.children = normalizeRoutes(page.children, metaImports, options).routes
} }
// Without a file, we can't use `definePageMeta` to extract route-level meta from the file // Without a file, we can't use `definePageMeta` to extract route-level meta from the file
@ -542,14 +546,14 @@ export function normalizeRoutes (routes: NuxtPage[], metaImports: Set<string> =
metaImports.add(` metaImports.add(`
let _createIslandPage let _createIslandPage
async function createIslandPage (name) { async function createIslandPage (name) {
_createIslandPage ||= await import(${JSON.stringify(resolve(distDir, 'components/runtime/server-component'))}).then(r => r.createIslandPage) _createIslandPage ||= await import(${JSON.stringify(options?.serverComponentRuntime)}).then(r => r.createIslandPage)
return _createIslandPage(name) return _createIslandPage(name)
};`) };`)
} else if (page.mode === 'client') { } else if (page.mode === 'client') {
metaImports.add(` metaImports.add(`
let _createClientPage let _createClientPage
async function createClientPage(loader) { async function createClientPage(loader) {
_createClientPage ||= await import(${JSON.stringify(resolve(distDir, 'components/runtime/client-component'))}).then(r => r.createClientPage) _createClientPage ||= await import(${JSON.stringify(options?.clientComponentRuntime)}).then(r => r.createClientPage)
return _createClientPage(loader); return _createClientPage(loader);
}`) }`)
} }
@ -562,7 +566,7 @@ async function createClientPage(loader) {
metaRoute.meta = `{ ...(${metaImportName} || {}), ...${route.meta} }` metaRoute.meta = `{ ...(${metaImportName} || {}), ...${route.meta} }`
} }
if (overrideMeta) { if (options?.overrideMeta) {
// skip and retain fallback if marked dynamic // skip and retain fallback if marked dynamic
// set to extracted value or fallback if none extracted // set to extracted value or fallback if none extracted
for (const key of ['name', 'path'] satisfies NormalizedRouteKeys) { for (const key of ['name', 'path'] satisfies NormalizedRouteKeys) {

View File

@ -92,7 +92,11 @@ function createTransformer (components: Component[], mode: 'client' | 'server' |
}, },
}, },
} as Nuxt } as Nuxt
const plugin = TransformPlugin(stubNuxt, () => components, mode).vite() const plugin = TransformPlugin(stubNuxt, {
mode,
getComponents: () => components,
serverComponentRuntime: '<repo>/nuxt/src/components/runtime/server-component',
}).vite()
return async (code: string, id: string) => { return async (code: string, id: string) => {
const result = await (plugin as any).transform!(code, id) const result = await (plugin as any).transform!(code, id)

View File

@ -168,7 +168,11 @@ describe('normalizeRoutes', () => {
page.meta.layout = 'test' page.meta.layout = 'test'
page.meta.foo = 'bar' page.meta.foo = 'bar'
const { routes, imports } = normalizeRoutes([page], new Set(), true) const { routes, imports } = normalizeRoutes([page], new Set(), {
clientComponentRuntime: '<client-component-runtime>',
serverComponentRuntime: '<server-component-runtime>',
overrideMeta: true,
})
expect({ routes, imports }).toMatchInlineSnapshot(` expect({ routes, imports }).toMatchInlineSnapshot(`
{ {
"imports": Set { "imports": Set {
@ -193,7 +197,11 @@ describe('normalizeRoutes', () => {
page.meta.layout = 'test' page.meta.layout = 'test'
page.meta.foo = 'bar' page.meta.foo = 'bar'
const { routes, imports } = normalizeRoutes([page], new Set()) const { routes, imports } = normalizeRoutes([page], new Set(), {
clientComponentRuntime: '<client-component-runtime>',
serverComponentRuntime: '<server-component-runtime>',
overrideMeta: false,
})
expect({ routes, imports }).toMatchInlineSnapshot(` expect({ routes, imports }).toMatchInlineSnapshot(`
{ {
"imports": Set { "imports": Set {

View File

@ -667,8 +667,18 @@ describe('pages:generateRoutesFromFiles', () => {
if (result) { if (result) {
expect(result).toEqual(test.output) expect(result).toEqual(test.output)
normalizedResults[test.description] = normalizeRoutes(result, new Set()).routes
normalizedOverrideMetaResults[test.description] = normalizeRoutes(result, new Set(), true).routes normalizedResults[test.description] = normalizeRoutes(result, new Set(), {
clientComponentRuntime: '<client-component-runtime>',
serverComponentRuntime: '<server-component-runtime>',
overrideMeta: false,
}).routes
normalizedOverrideMetaResults[test.description] = normalizeRoutes(result, new Set(), {
clientComponentRuntime: '<client-component-runtime>',
serverComponentRuntime: '<server-component-runtime>',
overrideMeta: true,
}).routes
} }
}) })
} }

View File

@ -424,7 +424,7 @@ export default defineUntypedSchema({
*/ */
alias: { alias: {
$resolve: async (val: Record<string, string>, get): Promise<Record<string, string>> => { $resolve: async (val: Record<string, string>, get): Promise<Record<string, string>> => {
const [srcDir, rootDir, assetsDir, publicDir] = await Promise.all([get('srcDir'), get('rootDir'), get('dir.assets'), get('dir.public')]) as [string, string, string, string] const [srcDir, rootDir, assetsDir, publicDir, buildDir] = await Promise.all([get('srcDir'), get('rootDir'), get('dir.assets'), get('dir.public'), get('buildDir')]) as [string, string, string, string, string]
return { return {
'~': srcDir, '~': srcDir,
'@': srcDir, '@': srcDir,
@ -432,6 +432,8 @@ export default defineUntypedSchema({
'@@': rootDir, '@@': rootDir,
[basename(assetsDir)]: resolve(srcDir, assetsDir), [basename(assetsDir)]: resolve(srcDir, assetsDir),
[basename(publicDir)]: resolve(srcDir, publicDir), [basename(publicDir)]: resolve(srcDir, publicDir),
'#build': buildDir,
'#internal/nuxt/paths': resolve(buildDir, 'paths.mjs'),
...val, ...val,
} }
}, },

View File

@ -109,9 +109,7 @@ export async function buildClient (ctx: ViteBuildContext) {
alias: { alias: {
...nodeCompat.alias, ...nodeCompat.alias,
...ctx.config.resolve?.alias, ...ctx.config.resolve?.alias,
'#internal/nuxt/paths': resolve(ctx.nuxt.options.buildDir, 'paths.mjs'), 'nitro/runtime': join(ctx.nuxt.options.buildDir, 'nitro.client.mjs'),
'#build/plugins': resolve(ctx.nuxt.options.buildDir, 'plugins/client'),
'nitro/runtime': resolve(ctx.nuxt.options.buildDir, 'nitro.client.mjs'),
}, },
dedupe: [ dedupe: [
'vue', 'vue',

View File

@ -1,48 +0,0 @@
import { dirname, isAbsolute, join, resolve } from 'pathe'
import type { Plugin } from 'vite'
const PREFIX = 'virtual:nuxt:'
export default function virtual (vfs: Record<string, string>): Plugin {
const extensions = ['', '.ts', '.vue', '.mjs', '.cjs', '.js', '.json']
const resolveWithExt = (id: string) => {
for (const ext of extensions) {
const rId = id + ext
if (rId in vfs) {
return rId
}
}
return null
}
return {
name: 'virtual',
resolveId (id, importer) {
if (process.platform === 'win32' && isAbsolute(id)) {
// Add back C: prefix on Windows
id = resolve(id)
}
const resolvedId = resolveWithExt(id)
if (resolvedId) { return PREFIX + resolvedId }
if (importer && !isAbsolute(id)) {
const importerNoPrefix = importer.startsWith(PREFIX) ? importer.slice(PREFIX.length) : importer
const importedDir = dirname(importerNoPrefix)
const resolved = resolveWithExt(join(importedDir, id))
if (resolved) { return PREFIX + resolved }
}
return null
},
load (id) {
if (!id.startsWith(PREFIX)) { return null }
const idNoPrefix = id.slice(PREFIX.length)
if (idNoPrefix in vfs) {
return {
code: vfs[idNoPrefix] || '',
map: null,
}
}
},
}
}

View File

@ -58,10 +58,6 @@ export async function buildServer (ctx: ViteBuildContext) {
}, },
resolve: { resolve: {
conditions: ((ctx.nuxt as any)._nitro as Nitro)?.options.exportConditions, conditions: ((ctx.nuxt as any)._nitro as Nitro)?.options.exportConditions,
alias: {
'#internal/nuxt/paths': resolve(ctx.nuxt.options.buildDir, 'paths.mjs'),
'#build/plugins': resolve(ctx.nuxt.options.buildDir, 'plugins/server'),
},
}, },
ssr: { ssr: {
external: [ external: [

View File

@ -41,7 +41,7 @@ export function viteNodePlugin (ctx: ViteBuildContext): VitePlugin {
configureServer (server) { configureServer (server) {
function invalidateVirtualModules () { function invalidateVirtualModules () {
for (const [id, mod] of server.moduleGraph.idToModuleMap) { for (const [id, mod] of server.moduleGraph.idToModuleMap) {
if (id.startsWith('virtual:')) { if (id.startsWith('virtual:') || id.startsWith('\0virtual:')) {
markInvalidate(mod) markInvalidate(mod)
} }
} }

View File

@ -12,7 +12,6 @@ import { resolveTSConfig } from 'pkg-types'
import { buildClient } from './client' import { buildClient } from './client'
import { buildServer } from './server' import { buildServer } from './server'
import virtual from './plugins/virtual'
import { warmupViteServer } from './utils/warmup' import { warmupViteServer } from './utils/warmup'
import { resolveCSSOptions } from './css' import { resolveCSSOptions } from './css'
import { composableKeysPlugin } from './plugins/composable-keys' import { composableKeysPlugin } from './plugins/composable-keys'
@ -65,10 +64,6 @@ export const bundle: NuxtBuilder['bundle'] = async (nuxt) => {
alias: { alias: {
...nuxt.options.alias, ...nuxt.options.alias,
'#app': nuxt.options.appDir, '#app': nuxt.options.appDir,
// We need this resolution to be present before the following entry, but it
// will be filled in client/server configs
'#build/plugins': '',
'#build': nuxt.options.buildDir,
'web-streams-polyfill/ponyfill/es2018': 'unenv/runtime/mock/empty', 'web-streams-polyfill/ponyfill/es2018': 'unenv/runtime/mock/empty',
// Cannot destructure property 'AbortController' of .. // Cannot destructure property 'AbortController' of ..
'abort-controller': 'unenv/runtime/mock/empty', 'abort-controller': 'unenv/runtime/mock/empty',
@ -110,7 +105,6 @@ export const bundle: NuxtBuilder['bundle'] = async (nuxt) => {
composables: nuxt.options.optimization.keyedComposables, composables: nuxt.options.optimization.keyedComposables,
}), }),
replace({ preventAssignment: true, ...globalThisReplacements }), replace({ preventAssignment: true, ...globalThisReplacements }),
virtual(nuxt.vfs),
], ],
server: { server: {
watch: { ignored: isIgnored }, watch: { ignored: isIgnored },
@ -224,7 +218,7 @@ export const bundle: NuxtBuilder['bundle'] = async (nuxt) => {
// Invalidate virtual modules when templates are re-generated // Invalidate virtual modules when templates are re-generated
ctx.nuxt.hook('app:templatesGenerated', () => { ctx.nuxt.hook('app:templatesGenerated', () => {
for (const [id, mod] of server.moduleGraph.idToModuleMap) { for (const [id, mod] of server.moduleGraph.idToModuleMap) {
if (id.startsWith('virtual:')) { if (id.startsWith('virtual:') || id.startsWith('\0virtual:')) {
server.moduleGraph.invalidateModule(mod) server.moduleGraph.invalidateModule(mod)
} }
} }

View File

@ -8,7 +8,6 @@ export default defineBuildConfig({
dependencies: [ dependencies: [
'@nuxt/kit', '@nuxt/kit',
'unplugin', 'unplugin',
'webpack-virtual-modules',
'postcss', 'postcss',
'postcss-loader', 'postcss-loader',
'vue-loader', 'vue-loader',

View File

@ -68,7 +68,6 @@
"webpack-bundle-analyzer": "^4.10.2", "webpack-bundle-analyzer": "^4.10.2",
"webpack-dev-middleware": "^7.4.2", "webpack-dev-middleware": "^7.4.2",
"webpack-hot-middleware": "^2.26.1", "webpack-hot-middleware": "^2.26.1",
"webpack-virtual-modules": "^0.6.2",
"webpackbar": "^6.0.1" "webpackbar": "^6.0.1"
}, },
"devDependencies": { "devDependencies": {

View File

@ -118,9 +118,6 @@ function basePlugins (ctx: WebpackConfigContext) {
function baseAlias (ctx: WebpackConfigContext) { function baseAlias (ctx: WebpackConfigContext) {
ctx.alias = { ctx.alias = {
'#app': ctx.options.appDir, '#app': ctx.options.appDir,
'#build/plugins': resolve(ctx.options.buildDir, 'plugins', ctx.isClient ? 'client' : 'server'),
'#build': ctx.options.buildDir,
'#internal/nuxt/paths': resolve(ctx.nuxt.options.buildDir, 'paths.mjs'),
...ctx.options.alias, ...ctx.options.alias,
...ctx.alias, ...ctx.alias,
} }

View File

@ -1,26 +0,0 @@
import { useNuxt } from '@nuxt/kit'
import VirtualModulesPlugin from 'webpack-virtual-modules'
export function registerVirtualModules () {
const nuxt = useNuxt()
// Initialize virtual modules instance
const virtualModules = new VirtualModulesPlugin(nuxt.vfs)
const writeFiles = () => {
for (const filePath in nuxt.vfs) {
virtualModules.writeModule(filePath, nuxt.vfs[filePath] || '')
}
}
// Workaround to initialize virtual modules
nuxt.hook('webpack:compile', ({ compiler }) => {
if (compiler.name === 'server') { writeFiles() }
})
// Update virtual modules when templates are updated
nuxt.hook('app:templatesGenerated', writeFiles)
nuxt.hook('webpack:config', configs => configs.forEach((config) => {
// Support virtual modules (input)
config.plugins!.push(virtualModules)
}))
}

View File

@ -17,7 +17,6 @@ import { composableKeysPlugin } from '../../vite/src/plugins/composable-keys'
import { DynamicBasePlugin } from './plugins/dynamic-base' import { DynamicBasePlugin } from './plugins/dynamic-base'
import { ChunkErrorPlugin } from './plugins/chunk' import { ChunkErrorPlugin } from './plugins/chunk'
import { createMFS } from './utils/mfs' import { createMFS } from './utils/mfs'
import { registerVirtualModules } from './virtual-modules'
import { client, server } from './configs' import { client, server } from './configs'
import { applyPresets, createWebpackConfigContext, getWebpackConfig } from './utils/config' import { applyPresets, createWebpackConfigContext, getWebpackConfig } from './utils/config'
import { dynamicRequire } from './nitro/plugins/dynamic-require' import { dynamicRequire } from './nitro/plugins/dynamic-require'
@ -26,8 +25,6 @@ import { dynamicRequire } from './nitro/plugins/dynamic-require'
// const plugins: string[] = [] // const plugins: string[] = []
export const bundle: NuxtBuilder['bundle'] = async (nuxt) => { export const bundle: NuxtBuilder['bundle'] = async (nuxt) => {
registerVirtualModules()
const webpackConfigs = await Promise.all([client, ...nuxt.options.ssr ? [server] : []].map(async (preset) => { const webpackConfigs = await Promise.all([client, ...nuxt.options.ssr ? [server] : []].map(async (preset) => {
const ctx = createWebpackConfigContext(nuxt) const ctx = createWebpackConfigContext(nuxt)
ctx.userConfig = defu(nuxt.options.webpack[`$${preset.name as 'client' | 'server'}`], ctx.userConfig) ctx.userConfig = defu(nuxt.options.webpack[`$${preset.name as 'client' | 'server'}`], ctx.userConfig)

View File

@ -911,9 +911,6 @@ importers:
webpack-hot-middleware: webpack-hot-middleware:
specifier: ^2.26.1 specifier: ^2.26.1
version: 2.26.1 version: 2.26.1
webpack-virtual-modules:
specifier: ^0.6.2
version: 0.6.2
webpackbar: webpackbar:
specifier: ^6.0.1 specifier: ^6.0.1
version: 6.0.1(webpack@5.95.0) version: 6.0.1(webpack@5.95.0)