Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(nuxt): add script block if there's none before island transformation #25148

Merged
merged 3 commits into from Jan 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 9 additions & 3 deletions packages/nuxt/src/components/islandsTransform.ts
Expand Up @@ -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'
Expand All @@ -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

Expand Down
25 changes: 25 additions & 0 deletions packages/nuxt/test/islandTransform.test.ts
Expand Up @@ -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', () => {
Expand Down