fix(nuxt): add missing script blocks before island transform (#25148)

This commit is contained in:
Julien Huang 2024-01-11 15:40:02 +01:00 committed by GitHub
parent 3c5ea3457c
commit 22800704f5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 3 deletions

View File

@ -33,6 +33,7 @@ const SCRIPT_RE = /<script[^>]*>/g
const HAS_SLOT_OR_CLIENT_RE = /(<slot[^>]*>)|(nuxt-client)/
const TEMPLATE_RE = /<template>([\s\S]*)<\/template>/
const NUXTCLIENT_ATTR_RE = /\snuxt-client(="[^"]*")?/g
const IMPORT_CODE = '\nimport { vforToArray as __vforToArray } from \'#app/components/utils\'' + '\nimport NuxtTeleportSsrClient from \'#app/components/nuxt-teleport-ssr-client\''
export const islandsTransform = createUnplugin((options: ServerOnlyComponentTransformPluginOptions, meta) => {
const isVite = meta.framework === 'vite'
@ -57,9 +58,14 @@ export const islandsTransform = createUnplugin((options: ServerOnlyComponentTran
const startingIndex = template.index || 0
const s = new MagicString(code)
s.replace(SCRIPT_RE, (full) => {
return full + '\nimport { vforToArray as __vforToArray } from \'#app/components/utils\'' + '\nimport NuxtTeleportSsrClient from \'#app/components/nuxt-teleport-ssr-client\''
})
if (!code.match(SCRIPT_RE)) {
s.prepend('<script setup>' + IMPORT_CODE + '</script>')
} else {
s.replace(SCRIPT_RE, (full) => {
return full + IMPORT_CODE
})
}
let hasNuxtClient = false

View File

@ -317,6 +317,31 @@ describe('islandTransform - server and island components', () => {
"
`)
})
it('should add import if there is no scripts in the SFC', async () => {
const result = await viteTransform(`<template>
<div>
<HelloWorld />
<HelloWorld nuxt-client />
</div>
</template>
`, 'hello.server.vue', false, true)
expect(result).toMatchInlineSnapshot(`
"<script setup>
import { vforToArray as __vforToArray } from '#app/components/utils'
import NuxtTeleportSsrClient from '#app/components/nuxt-teleport-ssr-client'</script><template>
<div>
<HelloWorld />
<NuxtTeleportSsrClient to="HelloWorld-CyH3UXLuYA" :nuxt-client="true"><HelloWorld /></NuxtTeleportSsrClient>
</div>
</template>
"
`)
expect(result).toContain(`import NuxtTeleportSsrClient from '#app/components/nuxt-teleport-ssr-client'`)
})
})
describe('webpack', () => {