chore: lint and types

This commit is contained in:
julien huang 2023-08-14 23:19:35 +02:00
parent e5ddf98fc0
commit aceb4ae29a
5 changed files with 41 additions and 35 deletions

View File

@ -1,9 +1,15 @@
import { relative } from 'node:path' import { relative } from 'node:path'
import type { Component } from 'vue'
import { Teleport, defineComponent, h } from 'vue' import { Teleport, defineComponent, h } from 'vue'
import { useNuxtApp } from '#app' import { useNuxtApp } from '#app'
// @ts-expect-error virtual file // @ts-expect-error virtual file
import { paths } from '#build/components-chunk' import { paths } from '#build/components-chunk'
type ExtendedComponent = Component & {
__file: string,
__name: string
}
/** /**
* component only used with componentsIsland * component only used with componentsIsland
* this teleport the component in SSR only if * this teleport the component in SSR only if
@ -34,12 +40,14 @@ export default defineComponent({
const islandContext = app.ssrContext!.islandContext! const islandContext = app.ssrContext!.islandContext!
const slot = slots.default!()[0] const slot = slots.default!()[0]
if (process.dev) { const slotType = (slot.type as ExtendedComponent)
const path = '_nuxt/' + relative(props.rootDir, slot.type.__file)
islandContext.chunks[slot.type.__name] = path if (process.dev) {
const path = '_nuxt/' + relative(props.rootDir, slotType.__file)
islandContext.chunks[slotType.__name] = path
} else { } else {
islandContext.chunks[slot.type.__name] = paths[slot.type.__name] islandContext.chunks[slotType.__name] = paths[slotType.__name]
} }
// todo chunk path in production // todo chunk path in production
islandContext.propsData[props.to] = slot.props || {} islandContext.propsData[props.to] = slot.props || {}

View File

@ -101,7 +101,8 @@ export default defineComponent({
style: [] style: []
}, },
chunks: {}, chunks: {},
props: {} props: {},
teleports: {}
}) })
} }
ssrHTML.value = renderedHTML ssrHTML.value = renderedHTML
@ -111,12 +112,13 @@ export default defineComponent({
const availableSlots = computed(() => [...ssrHTML.value.matchAll(SLOTNAME_RE)].map(m => m[1])) const availableSlots = computed(() => [...ssrHTML.value.matchAll(SLOTNAME_RE)].map(m => m[1]))
// no need for reactivity // no need for reactivity
// eslint-disable-next-line vue/no-setup-props-destructure
let interactiveProps: Record<string, Record<string, any>> = process.client && nuxtApp.isHydrating ? toRaw(nuxtApp.payload.data[`${props.name}_${hashId.value}_interactive`].props) : {} let interactiveProps: Record<string, Record<string, any>> = process.client && nuxtApp.isHydrating ? toRaw(nuxtApp.payload.data[`${props.name}_${hashId.value}_interactive`].props) : {}
const interactiveChunksList = process.client && nuxtApp.isHydrating ? nuxtApp.payload.data[`${props.name}_${hashId.value}_interactive`].chunks : {} const interactiveChunksList = process.client && nuxtApp.isHydrating ? nuxtApp.payload.data[`${props.name}_${hashId.value}_interactive`].chunks : {}
let interactiveTeleports = {} let interactiveTeleports: Record<string, string> = {}
const html = computed(() => { const html = computed(() => {
const currentSlots = Object.keys(slots) const currentSlots = Object.keys(slots)
let html = ssrHTML.value const html = ssrHTML.value
return html.replace(SLOT_FALLBACK_RE, (full, slotName, content) => { return html.replace(SLOT_FALLBACK_RE, (full, slotName, content) => {
// remove fallback to insert slots // remove fallback to insert slots
@ -236,15 +238,14 @@ let interactiveTeleports = {}
} }
if (process.server) { if (process.server) {
for (const [id, html] of Object.entries(interactiveTeleports)) { for (const [id, html] of Object.entries(interactiveTeleports)) {
nodes.push(createVNode(Teleport, { to: `uid=${uid.value};client=${id}` }, { nodes.push(createVNode(Teleport, { to: `uid=${uid.value};client=${id}` }, {
default: () => [createStaticVNode(html, 1)] default: () => [createStaticVNode(html, 1)]
})) }))
} }
} }
if (process.client && html.value.includes('nuxt-ssr-client')) { if (process.client && html.value.includes('nuxt-ssr-client')) {
for (const [id, props] of Object.entries(interactiveProps)) { for (const [id, props] of Object.entries(interactiveProps)) {
// @ts-expect-error _ is the components default export in build chunks
const component = components!.get(id.split('-')[0])!._ ?? components!.get(id.split('-')[0])! const component = components!.get(id.split('-')[0])!._ ?? components!.get(id.split('-')[0])!
const vnode = createVNode(Teleport, { to: `[nuxt-ssr-component-uid='${uid.value}'] [nuxt-ssr-client="${id}"]` }, { const vnode = createVNode(Teleport, { to: `[nuxt-ssr-component-uid='${uid.value}'] [nuxt-ssr-client="${id}"]` }, {
default: () => { default: () => {

View File

@ -134,17 +134,21 @@ export const componentsChunkPlugin = createUnplugin((options: ServerOnlyComponen
config.build = config.build || {} config.build = config.build || {}
config.build.rollupOptions = config.build.rollupOptions || {} config.build.rollupOptions = config.build.rollupOptions || {}
config.build.rollupOptions.output = config.build.rollupOptions.output || {} config.build.rollupOptions.output = config.build.rollupOptions.output || {}
if (Array.isArray(config.build.rollupOptions.output)) { const componentManualChunk = (id: string) => {
} else {
config.build.rollupOptions.output.manualChunks = (id, { getModuleIds, getModuleInfo }) => {
if (components.some(c => c.filePath === parseURL(decodeURIComponent(pathToFileURL(id).href)).pathname)) { if (components.some(c => c.filePath === parseURL(decodeURIComponent(pathToFileURL(id).href)).pathname)) {
return basename(id) return basename(id)
} }
} }
if (Array.isArray(config.build.rollupOptions.output)) {
config.build.rollupOptions.output.forEach((output) => {
output.manualChunks = componentManualChunk
})
} else {
config.build.rollupOptions.output.manualChunks = componentManualChunk
} }
}, },
generateBundle (opts, bundle) { generateBundle (_opts, bundle) {
const components = options.getComponents() const components = options.getComponents()
const componentsChunks = Object.entries(bundle).filter(([_chunkPath, chunkInfo]) => { const componentsChunks = Object.entries(bundle).filter(([_chunkPath, chunkInfo]) => {
if (chunkInfo.type !== 'chunk') { return false } if (chunkInfo.type !== 'chunk') { return false }
@ -162,8 +166,8 @@ export const componentsChunkPlugin = createUnplugin((options: ServerOnlyComponen
}) })
}) })
fs.writeFileSync(join(options.nuxt.options.buildDir, 'components-chunk.mjs'), `export const paths = /* #__PURE__ */ ${JSON.stringify(componentsChunks.reduce((acc, [chunkPath, chunkInfo]) => { fs.writeFileSync(join(options.nuxt.options.buildDir, 'components-chunk.mjs'), `export const paths = ${JSON.stringify(componentsChunks.reduce((acc, [chunkPath, chunkInfo]) => {
if (chunkInfo.type && chunkInfo.name && chunkInfo.exports && chunkInfo.exports.length > 0) { return Object.assign(acc, { [withoutClientSuffixAndExtension(chunkInfo.name)]: chunkPath }) } if (chunkInfo.type === 'chunk' && chunkInfo.name && chunkInfo.exports.length > 0) { return Object.assign(acc, { [withoutClientSuffixAndExtension(chunkInfo.name)]: chunkPath }) }
return acc return acc
}, {}))}`) }, {}))}`)
} }

View File

@ -279,10 +279,6 @@ async function initNuxt (nuxt: Nuxt) {
priority: 10, // built-in that we do not expect the user to override priority: 10, // built-in that we do not expect the user to override
filePath: resolve(nuxt.options.appDir, 'components/nuxt-island') filePath: resolve(nuxt.options.appDir, 'components/nuxt-island')
}) })
nuxt.hook('build:manifest', (manifest) => {
debugger
})
} }
// Add experimental cross-origin prefetch support using Speculation Rules API // Add experimental cross-origin prefetch support using Speculation Rules API

View File

@ -433,7 +433,7 @@ export default defineRenderHandler(async (event): Promise<Partial<RenderResponse
state: ssrContext.payload.state, state: ssrContext.payload.state,
chunks: islandContext.chunks, chunks: islandContext.chunks,
props: islandContext.propsData, props: islandContext.propsData,
teleports: ssrContext.teleports teleports: ssrContext.teleports || {}
} }
await nitroApp.hooks.callHook('render:island', islandResponse, { event, islandContext }) await nitroApp.hooks.callHook('render:island', islandResponse, { event, islandContext })
@ -595,21 +595,18 @@ function replaceServerOnlyComponentsSlots (ssrContext: NuxtSSRContext, html: str
return html return html
} }
function replaceClientTeleport (ssrContext: NuxtSSRContext, html: string) { function replaceClientTeleport (ssrContext: NuxtSSRContext, html: string) {
const { teleports, islandContext } = ssrContext const { teleports, islandContext } = ssrContext
if (islandContext || !teleports) { return html } if (islandContext || !teleports) { return html }
for (const key in teleports) { for (const key in teleports) {
const match = key.match(SSR_CLIENT_TELEPORT_MARKER) const match = key.match(SSR_CLIENT_TELEPORT_MARKER)
console.log(ssrContext.teleports)
if (!match) { continue } if (!match) { continue }
const [, uid, clientId] = match const [, uid, clientId] = match
if (!uid || !clientId) { continue } if (!uid || !clientId) { continue }
html = html.replace(new RegExp(`<div nuxt-ssr-component-uid="${uid}"[^>]*>((?!nuxt-ssr-client="${clientId}"|nuxt-ssr-component-uid)[\\s\\S])*<div [^>]*nuxt-ssr-client="${clientId}"[^>]*>`), (full) => { html = html.replace(new RegExp(`<div nuxt-ssr-component-uid="${uid}"[^>]*>((?!nuxt-ssr-client="${clientId}"|nuxt-ssr-component-uid)[\\s\\S])*<div [^>]*nuxt-ssr-client="${clientId}"[^>]*>`), (full) => {
return full + teleports[key] return full + teleports[key]
}) })
console.log(html, 'HTMLLLLLLLL')
} }
return html return html
} }