refactor: unify window.__NUXT__ structure for single and multi app

This commit is contained in:
Typed SIGTERM 2024-08-23 14:28:54 +00:00 committed by GitHub
parent 8785ed43f6
commit e1fcfad7a2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 15 additions and 33 deletions

View File

@ -9,7 +9,7 @@ import { useRoute } from './router'
import { getAppManifest, getRouteRules } from './manifest' import { getAppManifest, getRouteRules } from './manifest'
// @ts-expect-error virtual import // @ts-expect-error virtual import
import { appId, appManifest, multiApp, payloadExtraction, renderJsonPayloads } from '#build/nuxt.config.mjs' import { appId, appManifest, payloadExtraction, renderJsonPayloads } from '#build/nuxt.config.mjs'
interface LoadPayloadOptions { interface LoadPayloadOptions {
fresh?: boolean fresh?: boolean
@ -107,7 +107,7 @@ export async function getNuxtClientPayload () {
return payloadCache return payloadCache
} }
const el = multiApp ? document.querySelector(`[data-nuxt-data="${appId}"]`) as HTMLElement : document.getElementById('__NUXT_DATA__') const el = document.querySelector(`[data-nuxt-data="${appId}"]`) as HTMLElement
if (!el) { if (!el) {
return {} as Partial<NuxtPayload> return {} as Partial<NuxtPayload>
} }
@ -119,7 +119,7 @@ export async function getNuxtClientPayload () {
payloadCache = { payloadCache = {
...inlineData, ...inlineData,
...externalData, ...externalData,
...(multiApp ? window.__NUXT__?.[appId] : window.__NUXT__), ...window.__NUXT__?.[appId],
} }
if (payloadCache!.config?.public) { if (payloadCache!.config?.public) {

View File

@ -15,7 +15,7 @@ import plugins from '#build/plugins'
// @ts-expect-error virtual file // @ts-expect-error virtual file
import RootComponent from '#build/root-component.mjs' import RootComponent from '#build/root-component.mjs'
// @ts-expect-error virtual file // @ts-expect-error virtual file
import { appId, multiApp, vueAppRootContainer } from '#build/nuxt.config.mjs' import { appId, vueAppRootContainer } from '#build/nuxt.config.mjs'
let entry: (ssrContext?: CreateOptions['ssrContext']) => Promise<App<Element>> let entry: (ssrContext?: CreateOptions['ssrContext']) => Promise<App<Element>>
@ -52,8 +52,8 @@ if (import.meta.client) {
if (vueAppPromise) { return vueAppPromise } if (vueAppPromise) { return vueAppPromise }
const isSSR = Boolean( const isSSR = Boolean(
(multiApp ? window.__NUXT__?.[appId] : window.__NUXT__)?.serverRendered ?? window.__NUXT__?.[appId]?.serverRendered ??
(multiApp ? document.querySelector(`[data-nuxt-data="${appId}"]`) as HTMLElement : document.getElementById('__NUXT_DATA__'))?.dataset.ssr === 'true', (document.querySelector(`[data-nuxt-data="${appId}"]`) as HTMLElement)?.dataset.ssr === 'true',
) )
const vueApp = isSSR ? createSSRApp(RootComponent) : createApp(RootComponent) const vueApp = isSSR ? createSSRApp(RootComponent) : createApp(RootComponent)

View File

@ -21,7 +21,7 @@ import type { RouteAnnouncer } from '../app/composables/route-announcer'
import type { ViewTransition } from './plugins/view-transitions.client' import type { ViewTransition } from './plugins/view-transitions.client'
// @ts-expect-error virtual file // @ts-expect-error virtual file
import { appId, multiApp } from '#build/nuxt.config.mjs' import { appId } from '#build/nuxt.config.mjs'
import type { NuxtAppLiterals } from '#app' import type { NuxtAppLiterals } from '#app'
@ -311,7 +311,7 @@ export function createNuxtApp (options: CreateOptions) {
} }
if (import.meta.client) { if (import.meta.client) {
const __NUXT__ = multiApp ? window.__NUXT__?.[nuxtApp._id] : window.__NUXT__ const __NUXT__ = window.__NUXT__?.[nuxtApp._id]
// TODO: remove/refactor in https://github.com/nuxt/nuxt/issues/25336 // TODO: remove/refactor in https://github.com/nuxt/nuxt/issues/25336
if (__NUXT__) { if (__NUXT__) {
for (const key in __NUXT__) { for (const key in __NUXT__) {

View File

@ -26,7 +26,7 @@ declare global {
} }
interface Window { interface Window {
__NUXT__?: Record<string, any> | Record<string, Record<string, any>> __NUXT__?: Record<string, Record<string, any>>
useNuxtApp?: typeof useNuxtApp useNuxtApp?: typeof useNuxtApp
} }
} }

View File

@ -30,7 +30,7 @@ import { renderSSRHeadOptions } from '#internal/unhead.config.mjs'
import type { NuxtPayload, NuxtSSRContext } from '#app' import type { NuxtPayload, NuxtSSRContext } from '#app'
// @ts-expect-error virtual file // @ts-expect-error virtual file
import { appHead, appId, appRootAttrs, appRootTag, appTeleportAttrs, appTeleportTag, componentIslands, multiApp } from '#internal/nuxt.config.mjs' import { appHead, appId, appRootAttrs, appRootTag, appTeleportAttrs, appTeleportTag, componentIslands } from '#internal/nuxt.config.mjs'
// @ts-expect-error virtual file // @ts-expect-error virtual file
import { buildAssetsURL, publicAssetsURL } from '#internal/nuxt/paths' import { buildAssetsURL, publicAssetsURL } from '#internal/nuxt/paths'
@ -599,9 +599,6 @@ function renderPayloadJsonScript (opts: { ssrContext: NuxtSSRContext, data?: any
'data-nuxt-data': appId, 'data-nuxt-data': appId,
'data-ssr': !(process.env.NUXT_NO_SSR || opts.ssrContext.noSSR), 'data-ssr': !(process.env.NUXT_NO_SSR || opts.ssrContext.noSSR),
} }
if (!multiApp) {
payload.id = '__NUXT_DATA__'
}
if (opts.src) { if (opts.src) {
payload['data-src'] = opts.src payload['data-src'] = opts.src
} }
@ -609,9 +606,7 @@ function renderPayloadJsonScript (opts: { ssrContext: NuxtSSRContext, data?: any
return [ return [
payload, payload,
{ {
innerHTML: multiApp innerHTML: `window.__NUXT__=window.__NUXT__||{};window.__NUXT__[${JSON.stringify(appId)}]={config:${config}}`,
? `window.__NUXT__=window.__NUXT__||{};window.__NUXT__[${JSON.stringify(appId)}]={config:${config}}`
: `window.__NUXT__={};window.__NUXT__.config=${config}`,
}, },
] ]
} }
@ -621,20 +616,16 @@ function renderPayloadScript (opts: { ssrContext: NuxtSSRContext, data?: any, sr
const _PAYLOAD_EXTRACTION = import.meta.prerender && process.env.NUXT_PAYLOAD_EXTRACTION && !opts.ssrContext.noSSR const _PAYLOAD_EXTRACTION = import.meta.prerender && process.env.NUXT_PAYLOAD_EXTRACTION && !opts.ssrContext.noSSR
const nuxtData = devalue(opts.data) const nuxtData = devalue(opts.data)
if (_PAYLOAD_EXTRACTION) { if (_PAYLOAD_EXTRACTION) {
const singleAppPayload = `import p from "${opts.src}";window.__NUXT__={...p,...(${nuxtData})}`
const multiAppPayload = `import p from "${opts.src}";window.__NUXT__=window.__NUXT__||{};window.__NUXT__[${JSON.stringify(appId)}]={...p,...(${nuxtData})}`
return [ return [
{ {
type: 'module', type: 'module',
innerHTML: multiApp ? multiAppPayload : singleAppPayload, innerHTML: `import p from "${opts.src}";window.__NUXT__=window.__NUXT__||{};window.__NUXT__[${JSON.stringify(appId)}]={...p,...(${nuxtData})}`,
}, },
] ]
} }
const singleAppPayload = `window.__NUXT__=${nuxtData}`
const multiAppPayload = `window.__NUXT__=window.__NUXT__||{};window.__NUXT__[${JSON.stringify(appId)}]=${nuxtData}`
return [ return [
{ {
innerHTML: multiApp ? multiAppPayload : singleAppPayload, innerHTML: `window.__NUXT__=window.__NUXT__||{};window.__NUXT__[${JSON.stringify(appId)}]=${nuxtData}`,
}, },
] ]
} }

View File

@ -353,10 +353,7 @@ export const clientConfigTemplate: NuxtTemplate = {
const appId = JSON.stringify(nuxt.options.appId) const appId = JSON.stringify(nuxt.options.appId)
return [ return [
'export const useRuntimeConfig = () => ', 'export const useRuntimeConfig = () => ',
(!nuxt.options.future.multiApp `window?.__NUXT__?.[${appId}]?.config || window?.useNuxtApp?.(${appId}).payload?.config`,
? 'window?.__NUXT__?.config || window?.useNuxtApp?.().payload?.config'
: `window?.__NUXT__?.[${appId}]?.config || window?.useNuxtApp?.(${appId}).payload?.config`)
|| {},
].join('\n') ].join('\n')
}, },
} }
@ -503,7 +500,6 @@ export const nuxtConfigTemplate: NuxtTemplate = {
`export const viewTransition = ${ctx.nuxt.options.experimental.viewTransition}`, `export const viewTransition = ${ctx.nuxt.options.experimental.viewTransition}`,
`export const appId = ${JSON.stringify(ctx.nuxt.options.appId)}`, `export const appId = ${JSON.stringify(ctx.nuxt.options.appId)}`,
`export const outdatedBuildInterval = ${ctx.nuxt.options.experimental.checkOutdatedBuildInterval}`, `export const outdatedBuildInterval = ${ctx.nuxt.options.experimental.checkOutdatedBuildInterval}`,
`export const multiApp = ${!!ctx.nuxt.options.future.multiApp}`,
].join('\n\n') ].join('\n\n')
}, },
} }

View File

@ -13,11 +13,6 @@ export default defineUntypedSchema({
* @type {4} * @type {4}
*/ */
compatibilityVersion: 4, compatibilityVersion: 4,
/**
* This enables early access to the experimental multi-app support.
* @see [Nuxt Issue #21635](https://github.com/nuxt/nuxt/issues/21635)
*/
multiApp: false,
/** /**
* This enables 'Bundler' module resolution mode for TypeScript, which is the recommended setting * This enables 'Bundler' module resolution mode for TypeScript, which is the recommended setting
* for frameworks like Nuxt and Vite. * for frameworks like Nuxt and Vite.

View File

@ -1,5 +1,5 @@
export default defineNuxtPlugin((nuxtApp) => { export default defineNuxtPlugin((nuxtApp) => {
if (nuxtApp.payload.serverRendered && nuxtApp.payload.blinkable !== '<revivified-blink>' && document.querySelector('#__NUXT_DATA__')) { if (nuxtApp.payload.serverRendered && nuxtApp.payload.blinkable !== '<revivified-blink>' && document.querySelector('[data-nuxt-data]')) {
throw createError({ throw createError({
message: 'Custom type in Nuxt payload was not revived correctly', message: 'Custom type in Nuxt payload was not revived correctly',
}) })