mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-21 21:25:11 +00:00
refactor(nuxt,schema,vite,webpack): use unplugin for vfs (#29165)
This commit is contained in:
parent
e95edac5d9
commit
56d2261471
@ -223,13 +223,10 @@ export async function _generateTypes (nuxt: Nuxt) {
|
||||
exclude: [...exclude],
|
||||
} satisfies TSConfig)
|
||||
|
||||
const aliases: Record<string, string> = {
|
||||
...nuxt.options.alias,
|
||||
'#build': nuxt.options.buildDir,
|
||||
}
|
||||
const aliases: Record<string, string> = nuxt.options.alias
|
||||
|
||||
// Exclude bridge alias types to support Volar
|
||||
const excludedAlias = [/^@vue\/.*$/]
|
||||
const excludedAlias = [/^@vue\/.*$/, /^#internal\/nuxt/]
|
||||
|
||||
const basePath = tsConfig.compilerOptions!.baseUrl
|
||||
? resolve(nuxt.options.buildDir, tsConfig.compilerOptions!.baseUrl)
|
||||
|
@ -34,9 +34,6 @@ describe('tsConfig generation', () => {
|
||||
const { tsConfig } = await _generateTypes(mockNuxt)
|
||||
expect(tsConfig.compilerOptions?.paths).toMatchInlineSnapshot(`
|
||||
{
|
||||
"#build": [
|
||||
".",
|
||||
],
|
||||
"some-custom-alias": [
|
||||
"../some-alias",
|
||||
],
|
||||
|
@ -1,6 +1,6 @@
|
||||
import { existsSync, statSync, writeFileSync } from 'node:fs'
|
||||
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 { distDir } from '../dirs'
|
||||
@ -32,7 +32,7 @@ export default defineNuxtModule<ComponentsOptions>({
|
||||
defaults: {
|
||||
dirs: [],
|
||||
},
|
||||
setup (componentOptions, nuxt) {
|
||||
async setup (componentOptions, nuxt) {
|
||||
let componentDirs: ComponentsDir[] = []
|
||||
const context = {
|
||||
components: [] as Component[],
|
||||
@ -134,8 +134,9 @@ export default defineNuxtModule<ComponentsOptions>({
|
||||
addTemplate(componentsMetadataTemplate)
|
||||
}
|
||||
|
||||
addBuildPlugin(TransformPlugin(nuxt, getComponents, 'server'), { server: true, client: false })
|
||||
addBuildPlugin(TransformPlugin(nuxt, getComponents, 'client'), { server: false, client: true })
|
||||
const serverComponentRuntime = await findPath(join(distDir, 'components/runtime/server-component')) ?? join(distDir, 'components/runtime/server-component')
|
||||
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
|
||||
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
|
||||
nuxt.hook('app:templates', async (app) => {
|
||||
@ -222,6 +223,7 @@ export default defineNuxtModule<ComponentsOptions>({
|
||||
|
||||
const sharedLoaderOptions = {
|
||||
getComponents,
|
||||
serverComponentRuntime,
|
||||
transform: typeof nuxt.options.components === 'object' && !Array.isArray(nuxt.options.components) ? nuxt.options.components.transform : undefined,
|
||||
experimentalComponentIslands: !!nuxt.options.experimental.componentIslands,
|
||||
}
|
||||
|
@ -2,16 +2,16 @@ import { createUnplugin } from 'unplugin'
|
||||
import { genDynamicImport, genImport } from 'knitwork'
|
||||
import MagicString from 'magic-string'
|
||||
import { pascalCase } from 'scule'
|
||||
import { relative, resolve } from 'pathe'
|
||||
import { relative } from 'pathe'
|
||||
import type { Component, ComponentsOptions } from 'nuxt/schema'
|
||||
|
||||
import { logger, tryUseNuxt } from '@nuxt/kit'
|
||||
import { distDir } from '../../dirs'
|
||||
import { isVue } from '../../core/utils'
|
||||
|
||||
interface LoaderOptions {
|
||||
getComponents (): Component[]
|
||||
mode: 'server' | 'client'
|
||||
serverComponentRuntime: string
|
||||
sourcemap?: boolean
|
||||
transform?: ComponentsOptions['transform']
|
||||
experimentalComponentIslands?: boolean
|
||||
@ -20,7 +20,6 @@ interface LoaderOptions {
|
||||
export const LoaderPlugin = (options: LoaderOptions) => createUnplugin(() => {
|
||||
const exclude = options.transform?.exclude || []
|
||||
const include = options.transform?.include || []
|
||||
const serverComponentRuntime = resolve(distDir, 'components/runtime/server-component')
|
||||
const nuxt = tryUseNuxt()
|
||||
|
||||
return {
|
||||
@ -62,7 +61,7 @@ export const LoaderPlugin = (options: LoaderOptions) => createUnplugin(() => {
|
||||
const isServerOnly = !component._raw && component.mode === 'server' &&
|
||||
!components.some(c => c.pascalName === component.pascalName && c.mode === 'client')
|
||||
if (isServerOnly) {
|
||||
imports.add(genImport(serverComponentRuntime, [{ name: 'createServerComponent' }]))
|
||||
imports.add(genImport(options.serverComponentRuntime, [{ name: 'createServerComponent' }]))
|
||||
imports.add(`const ${identifier} = createServerComponent(${JSON.stringify(component.pascalName)})`)
|
||||
if (!options.experimentalComponentIslands) {
|
||||
logger.warn(`Standalone server components (\`${name}\`) are not yet supported without enabling \`experimental.componentIslands\`.`)
|
||||
|
@ -5,15 +5,19 @@ import { createUnimport } from 'unimport'
|
||||
import { createUnplugin } from 'unplugin'
|
||||
import { parseURL } from 'ufo'
|
||||
import { parseQuery } from 'vue-router'
|
||||
import { normalize, resolve } from 'pathe'
|
||||
import { normalize } from 'pathe'
|
||||
import { genImport } from 'knitwork'
|
||||
import { distDir } from '../../dirs'
|
||||
import type { getComponentsT } from '../module'
|
||||
|
||||
const COMPONENT_QUERY_RE = /[?&]nuxt_component=/
|
||||
|
||||
export function TransformPlugin (nuxt: Nuxt, getComponents: getComponentsT, mode: 'client' | 'server' | 'all') {
|
||||
const serverComponentRuntime = resolve(distDir, 'components/runtime/server-component')
|
||||
interface TransformPluginOptions {
|
||||
getComponents: getComponentsT
|
||||
mode: 'client' | 'server' | 'all'
|
||||
serverComponentRuntime: string
|
||||
}
|
||||
|
||||
export function TransformPlugin (nuxt: Nuxt, options: TransformPluginOptions) {
|
||||
const componentUnimport = createUnimport({
|
||||
imports: [
|
||||
{
|
||||
@ -26,7 +30,7 @@ export function TransformPlugin (nuxt: Nuxt, getComponents: getComponentsT, mode
|
||||
})
|
||||
|
||||
function getComponentsImports (): Import[] {
|
||||
const components = getComponents(mode)
|
||||
const components = options.getComponents(options.mode)
|
||||
return components.flatMap((c): Import[] => {
|
||||
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'}`
|
||||
@ -95,7 +99,7 @@ export function TransformPlugin (nuxt: Nuxt, getComponents: getComponentsT, mode
|
||||
const name = query.nuxt_component_name
|
||||
return {
|
||||
code: [
|
||||
`import { createServerComponent } from ${JSON.stringify(serverComponentRuntime)}`,
|
||||
`import { createServerComponent } from ${JSON.stringify(options.serverComponentRuntime)}`,
|
||||
`${exportWording} createServerComponent(${JSON.stringify(name)})`,
|
||||
].join('\n'),
|
||||
map: null,
|
||||
|
@ -33,8 +33,9 @@ export const TreeShakeTemplatePlugin = (options: TreeShakeTemplatePluginOptions)
|
||||
const components = options.getComponents()
|
||||
|
||||
if (!regexpMap.has(components)) {
|
||||
const serverPlaceholderPath = resolve(distDir, 'app/components/server-placeholder')
|
||||
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('-', '_')])
|
||||
.concat(['ClientOnly', 'client_only'])
|
||||
|
||||
|
@ -72,7 +72,7 @@ export async function generateApp (nuxt: Nuxt, app: NuxtApp, options: { filter?:
|
||||
if (template.modified) {
|
||||
nuxt.vfs[fullPath] = contents
|
||||
|
||||
const aliasPath = '#build/' + template.filename!.replace(/\.\w+$/, '')
|
||||
const aliasPath = '#build/' + template.filename
|
||||
nuxt.vfs[aliasPath] = contents
|
||||
|
||||
// In case a non-normalized absolute path is called for on Windows
|
||||
|
@ -101,8 +101,8 @@ export async function initNitro (nuxt: Nuxt & { _nitro?: Nitro }) {
|
||||
devHandlers: [],
|
||||
baseURL: nuxt.options.app.baseURL,
|
||||
virtual: {
|
||||
'#internal/nuxt.config.mjs': () => nuxt.vfs['#build/nuxt.config'],
|
||||
'#internal/nuxt/app-config': () => nuxt.vfs['#build/app.config']?.replace(/\/\*\* client \*\*\/[\s\S]*\/\*\* client-end \*\*\//, ''),
|
||||
'#internal/nuxt.config.mjs': () => nuxt.vfs['#build/nuxt.config.mjs'],
|
||||
'#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))}`,
|
||||
},
|
||||
routeRules: {
|
||||
@ -189,11 +189,11 @@ export async function initNitro (nuxt: Nuxt & { _nitro?: Nitro }) {
|
||||
},
|
||||
'@vue/devtools-api': 'vue-devtools-stub',
|
||||
|
||||
// Paths
|
||||
'#internal/nuxt/paths': resolve(distDir, 'core/runtime/nitro/paths'),
|
||||
|
||||
// Nuxt aliases
|
||||
...nuxt.options.alias,
|
||||
|
||||
// Paths
|
||||
'#internal/nuxt/paths': resolve(distDir, 'core/runtime/nitro/paths'),
|
||||
},
|
||||
replace: {
|
||||
'process.env.NUXT_NO_SSR': nuxt.options.ssr === false,
|
||||
|
@ -44,6 +44,7 @@ import { RemovePluginMetadataPlugin } from './plugins/plugin-metadata'
|
||||
import { AsyncContextInjectionPlugin } from './plugins/async-context'
|
||||
import { resolveDeepImportsPlugin } from './plugins/resolve-deep-imports'
|
||||
import { prehydrateTransformPlugin } from './plugins/prehydrate'
|
||||
import { VirtualFSPlugin } from './plugins/virtual'
|
||||
|
||||
export function createNuxt (options: NuxtOptions): Nuxt {
|
||||
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
|
||||
addBuildPlugin(RemovePluginMetadataPlugin(nuxt))
|
||||
|
||||
|
@ -16,7 +16,7 @@ export function resolveDeepImportsPlugin (nuxt: Nuxt): Plugin {
|
||||
conditions = config.mode === 'test' ? [...config.resolve.conditions, 'import', 'require'] : config.resolve.conditions
|
||||
},
|
||||
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
|
||||
}
|
||||
|
||||
|
67
packages/nuxt/src/core/plugins/virtual.ts
Normal file
67
packages/nuxt/src/core/plugins/virtual.ts
Normal 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
|
||||
}
|
@ -58,7 +58,7 @@ export const cssTemplate: NuxtTemplate = {
|
||||
}
|
||||
|
||||
export const clientPluginTemplate: NuxtTemplate = {
|
||||
filename: 'plugins/client.mjs',
|
||||
filename: 'plugins.client.mjs',
|
||||
async getContents (ctx) {
|
||||
const clientPlugins = await annotatePlugins(ctx.nuxt, ctx.app.plugins.filter(p => !p.mode || p.mode !== 'server'))
|
||||
checkForCircularDependencies(clientPlugins)
|
||||
@ -78,7 +78,7 @@ export const clientPluginTemplate: NuxtTemplate = {
|
||||
}
|
||||
|
||||
export const serverPluginTemplate: NuxtTemplate = {
|
||||
filename: 'plugins/server.mjs',
|
||||
filename: 'plugins.server.mjs',
|
||||
async getContents (ctx) {
|
||||
const serverPlugins = await annotatePlugins(ctx.nuxt, ctx.app.plugins.filter(p => !p.mode || p.mode !== 'client'))
|
||||
checkForCircularDependencies(serverPlugins)
|
||||
|
@ -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
|
||||
nuxt.hooks.hook('nitro:config', (config) => {
|
||||
config.virtual!['#internal/unhead-plugins.mjs'] = () => nuxt.vfs['#build/unhead-plugins']
|
||||
config.virtual!['#internal/unhead.config.mjs'] = () => nuxt.vfs['#build/unhead.config']
|
||||
config.virtual!['#internal/unhead-plugins.mjs'] = () => nuxt.vfs['#build/unhead-plugins.mjs']
|
||||
config.virtual!['#internal/unhead.config.mjs'] = () => nuxt.vfs['#build/unhead.config.mjs']
|
||||
})
|
||||
|
||||
// Add library-specific plugin
|
||||
|
@ -52,7 +52,7 @@ export default defineNuxtModule({
|
||||
}
|
||||
|
||||
// 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)
|
||||
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
|
||||
addTemplate({
|
||||
filename: 'routes.mjs',
|
||||
getContents ({ app }) {
|
||||
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')
|
||||
},
|
||||
})
|
||||
|
@ -15,7 +15,6 @@ import type { NuxtPage } from 'nuxt/schema'
|
||||
|
||||
import { getLoader, uniqueBy } from '../core/utils'
|
||||
import { toArray } from '../utils'
|
||||
import { distDir } from '../dirs'
|
||||
|
||||
enum SegmentParserState {
|
||||
initial,
|
||||
@ -476,7 +475,12 @@ function serializeRouteValue (value: any, skipSerialisation = false) {
|
||||
|
||||
type NormalizedRoute = Partial<Record<Exclude<keyof NuxtPage, 'file'>, string>> & { component?: string }
|
||||
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 {
|
||||
imports: metaImports,
|
||||
routes: genArrayFromRaw(routes.map((page) => {
|
||||
@ -506,7 +510,7 @@ export function normalizeRoutes (routes: NuxtPage[], metaImports: Set<string> =
|
||||
}
|
||||
|
||||
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
|
||||
@ -542,14 +546,14 @@ export function normalizeRoutes (routes: NuxtPage[], metaImports: Set<string> =
|
||||
metaImports.add(`
|
||||
let _createIslandPage
|
||||
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)
|
||||
};`)
|
||||
} else if (page.mode === 'client') {
|
||||
metaImports.add(`
|
||||
let _createClientPage
|
||||
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);
|
||||
}`)
|
||||
}
|
||||
@ -562,7 +566,7 @@ async function createClientPage(loader) {
|
||||
metaRoute.meta = `{ ...(${metaImportName} || {}), ...${route.meta} }`
|
||||
}
|
||||
|
||||
if (overrideMeta) {
|
||||
if (options?.overrideMeta) {
|
||||
// skip and retain fallback if marked dynamic
|
||||
// set to extracted value or fallback if none extracted
|
||||
for (const key of ['name', 'path'] satisfies NormalizedRouteKeys) {
|
||||
|
@ -92,7 +92,11 @@ function createTransformer (components: Component[], mode: 'client' | 'server' |
|
||||
},
|
||||
},
|
||||
} 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) => {
|
||||
const result = await (plugin as any).transform!(code, id)
|
||||
|
@ -168,7 +168,11 @@ describe('normalizeRoutes', () => {
|
||||
page.meta.layout = 'test'
|
||||
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(`
|
||||
{
|
||||
"imports": Set {
|
||||
@ -193,7 +197,11 @@ describe('normalizeRoutes', () => {
|
||||
page.meta.layout = 'test'
|
||||
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(`
|
||||
{
|
||||
"imports": Set {
|
||||
|
@ -667,8 +667,18 @@ describe('pages:generateRoutesFromFiles', () => {
|
||||
|
||||
if (result) {
|
||||
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
|
||||
}
|
||||
})
|
||||
}
|
||||
|
@ -424,7 +424,7 @@ export default defineUntypedSchema({
|
||||
*/
|
||||
alias: {
|
||||
$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 {
|
||||
'~': srcDir,
|
||||
'@': srcDir,
|
||||
@ -432,6 +432,8 @@ export default defineUntypedSchema({
|
||||
'@@': rootDir,
|
||||
[basename(assetsDir)]: resolve(srcDir, assetsDir),
|
||||
[basename(publicDir)]: resolve(srcDir, publicDir),
|
||||
'#build': buildDir,
|
||||
'#internal/nuxt/paths': resolve(buildDir, 'paths.mjs'),
|
||||
...val,
|
||||
}
|
||||
},
|
||||
|
@ -109,9 +109,7 @@ export async function buildClient (ctx: ViteBuildContext) {
|
||||
alias: {
|
||||
...nodeCompat.alias,
|
||||
...ctx.config.resolve?.alias,
|
||||
'#internal/nuxt/paths': resolve(ctx.nuxt.options.buildDir, 'paths.mjs'),
|
||||
'#build/plugins': resolve(ctx.nuxt.options.buildDir, 'plugins/client'),
|
||||
'nitro/runtime': resolve(ctx.nuxt.options.buildDir, 'nitro.client.mjs'),
|
||||
'nitro/runtime': join(ctx.nuxt.options.buildDir, 'nitro.client.mjs'),
|
||||
},
|
||||
dedupe: [
|
||||
'vue',
|
||||
|
@ -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,
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
@ -58,10 +58,6 @@ export async function buildServer (ctx: ViteBuildContext) {
|
||||
},
|
||||
resolve: {
|
||||
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: {
|
||||
external: [
|
||||
|
@ -41,7 +41,7 @@ export function viteNodePlugin (ctx: ViteBuildContext): VitePlugin {
|
||||
configureServer (server) {
|
||||
function invalidateVirtualModules () {
|
||||
for (const [id, mod] of server.moduleGraph.idToModuleMap) {
|
||||
if (id.startsWith('virtual:')) {
|
||||
if (id.startsWith('virtual:') || id.startsWith('\0virtual:')) {
|
||||
markInvalidate(mod)
|
||||
}
|
||||
}
|
||||
|
@ -12,7 +12,6 @@ import { resolveTSConfig } from 'pkg-types'
|
||||
|
||||
import { buildClient } from './client'
|
||||
import { buildServer } from './server'
|
||||
import virtual from './plugins/virtual'
|
||||
import { warmupViteServer } from './utils/warmup'
|
||||
import { resolveCSSOptions } from './css'
|
||||
import { composableKeysPlugin } from './plugins/composable-keys'
|
||||
@ -65,10 +64,6 @@ export const bundle: NuxtBuilder['bundle'] = async (nuxt) => {
|
||||
alias: {
|
||||
...nuxt.options.alias,
|
||||
'#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',
|
||||
// Cannot destructure property 'AbortController' of ..
|
||||
'abort-controller': 'unenv/runtime/mock/empty',
|
||||
@ -110,7 +105,6 @@ export const bundle: NuxtBuilder['bundle'] = async (nuxt) => {
|
||||
composables: nuxt.options.optimization.keyedComposables,
|
||||
}),
|
||||
replace({ preventAssignment: true, ...globalThisReplacements }),
|
||||
virtual(nuxt.vfs),
|
||||
],
|
||||
server: {
|
||||
watch: { ignored: isIgnored },
|
||||
@ -224,7 +218,7 @@ export const bundle: NuxtBuilder['bundle'] = async (nuxt) => {
|
||||
// Invalidate virtual modules when templates are re-generated
|
||||
ctx.nuxt.hook('app:templatesGenerated', () => {
|
||||
for (const [id, mod] of server.moduleGraph.idToModuleMap) {
|
||||
if (id.startsWith('virtual:')) {
|
||||
if (id.startsWith('virtual:') || id.startsWith('\0virtual:')) {
|
||||
server.moduleGraph.invalidateModule(mod)
|
||||
}
|
||||
}
|
||||
|
@ -8,7 +8,6 @@ export default defineBuildConfig({
|
||||
dependencies: [
|
||||
'@nuxt/kit',
|
||||
'unplugin',
|
||||
'webpack-virtual-modules',
|
||||
'postcss',
|
||||
'postcss-loader',
|
||||
'vue-loader',
|
||||
|
@ -68,7 +68,6 @@
|
||||
"webpack-bundle-analyzer": "^4.10.2",
|
||||
"webpack-dev-middleware": "^7.4.2",
|
||||
"webpack-hot-middleware": "^2.26.1",
|
||||
"webpack-virtual-modules": "^0.6.2",
|
||||
"webpackbar": "^6.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
@ -118,9 +118,6 @@ function basePlugins (ctx: WebpackConfigContext) {
|
||||
function baseAlias (ctx: WebpackConfigContext) {
|
||||
ctx.alias = {
|
||||
'#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.alias,
|
||||
}
|
||||
|
@ -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)
|
||||
}))
|
||||
}
|
@ -17,7 +17,6 @@ import { composableKeysPlugin } from '../../vite/src/plugins/composable-keys'
|
||||
import { DynamicBasePlugin } from './plugins/dynamic-base'
|
||||
import { ChunkErrorPlugin } from './plugins/chunk'
|
||||
import { createMFS } from './utils/mfs'
|
||||
import { registerVirtualModules } from './virtual-modules'
|
||||
import { client, server } from './configs'
|
||||
import { applyPresets, createWebpackConfigContext, getWebpackConfig } from './utils/config'
|
||||
import { dynamicRequire } from './nitro/plugins/dynamic-require'
|
||||
@ -26,8 +25,6 @@ import { dynamicRequire } from './nitro/plugins/dynamic-require'
|
||||
// const plugins: string[] = []
|
||||
|
||||
export const bundle: NuxtBuilder['bundle'] = async (nuxt) => {
|
||||
registerVirtualModules()
|
||||
|
||||
const webpackConfigs = await Promise.all([client, ...nuxt.options.ssr ? [server] : []].map(async (preset) => {
|
||||
const ctx = createWebpackConfigContext(nuxt)
|
||||
ctx.userConfig = defu(nuxt.options.webpack[`$${preset.name as 'client' | 'server'}`], ctx.userConfig)
|
||||
|
@ -911,9 +911,6 @@ importers:
|
||||
webpack-hot-middleware:
|
||||
specifier: ^2.26.1
|
||||
version: 2.26.1
|
||||
webpack-virtual-modules:
|
||||
specifier: ^0.6.2
|
||||
version: 0.6.2
|
||||
webpackbar:
|
||||
specifier: ^6.0.1
|
||||
version: 6.0.1(webpack@5.95.0)
|
||||
|
Loading…
Reference in New Issue
Block a user