fix(nuxt): don't strip literals from template in <DevOnly> (#24511)

This commit is contained in:
Julien Huang 2023-11-28 22:49:47 +01:00 committed by GitHub
parent e3b8b84a24
commit f98aa5d44a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 3 deletions

View File

@ -1,4 +1,3 @@
import { stripLiteral } from 'strip-literal'
import MagicString from 'magic-string' import MagicString from 'magic-string'
import { createUnplugin } from 'unplugin' import { createUnplugin } from 'unplugin'
import { type Node, parse } from 'ultrahtml' import { type Node, parse } from 'ultrahtml'
@ -22,8 +21,7 @@ export const DevOnlyPlugin = createUnplugin((options: DevOnlyPluginOptions) => {
if (!DEVONLY_COMP_SINGLE_RE.test(code)) { return } if (!DEVONLY_COMP_SINGLE_RE.test(code)) { return }
const s = new MagicString(code) const s = new MagicString(code)
const strippedCode = stripLiteral(code) for (const match of code.matchAll(DEVONLY_COMP_RE) || []) {
for (const match of strippedCode.matchAll(DEVONLY_COMP_RE) || []) {
const ast: Node = parse(match[0]).children[0] const ast: Node = parse(match[0]).children[0]
const fallback: Node | undefined = ast.children?.find((n: Node) => n.name === 'template' && Object.values(n.attributes).includes('#fallback')) const fallback: Node | undefined = ast.children?.find((n: Node) => n.name === 'template' && Object.values(n.attributes).includes('#fallback'))
const replacement = fallback ? match[0].slice(fallback.loc[0].end, fallback.loc[fallback.loc.length - 1].start) : '' const replacement = fallback ? match[0].slice(fallback.loc[0].end, fallback.loc[fallback.loc.length - 1].start) : ''

View File

@ -56,4 +56,27 @@ describe('test devonly transform ', () => {
expect(result).not.toContain('lazy-dev-only') expect(result).not.toContain('lazy-dev-only')
expect(result).not.toContain('LazyDevOnly') expect(result).not.toContain('LazyDevOnly')
}) })
it('should not remove class -> nuxt#24491', async () => {
const source = `<template>
<DevOnly>
<div class="red">This is red.</div>
<template #fallback>
<div class="red">This should also be red.</div>
</template>
</DevOnly>
</template>
`
const result = await viteTransform(source, 'some id')
expect(result).toMatchInlineSnapshot(`
"<template>
<div class=\\"red\\">This should also be red.</div>
</template>
"
`)
})
}) })