fix(nuxt): get fallback for <DevOnly> from parsed html (#20840)

This commit is contained in:
Inesh Bose 2023-05-15 13:33:46 +01:00 committed by GitHub
parent d1a5719cbc
commit 1f30cf18e3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 16 additions and 2 deletions

View File

@ -338,6 +338,7 @@ The content will not be included in production builds and tree-shaken.
<LazyDebugBar />
<!-- if you ever require to have a replacement during production -->
<!-- be sure to test these using `nuxt preview` -->
<template #fallback>
<div><!-- empty div for flex.justify-between --></div>
</template>

View File

@ -90,6 +90,7 @@
"scule": "^1.0.0",
"strip-literal": "^1.0.1",
"ufo": "^1.1.2",
"ultrahtml": "^1.2.0",
"unctx": "^2.3.0",
"unenv": "^1.4.1",
"unimport": "^3.0.6",

View File

@ -3,13 +3,14 @@ import { stripLiteral } from 'strip-literal'
import { parseQuery, parseURL } from 'ufo'
import MagicString from 'magic-string'
import { createUnplugin } from 'unplugin'
import { type Node, parse } from 'ultrahtml'
interface DevOnlyPluginOptions {
sourcemap?: boolean
}
export const DevOnlyPlugin = createUnplugin((options: DevOnlyPluginOptions) => {
const DEVONLY_COMP_RE = /<(?:dev-only|DevOnly)>[^<]*(?:<template\s+#fallback>(?<fallback>[\s\S]*?)<\/template>)?[\s\S]*?<\/(?:dev-only|DevOnly)>/g
const DEVONLY_COMP_RE = /<(?:dev-only|DevOnly)>[\s\S]*?<\/(?:dev-only|DevOnly)>/g
return {
name: 'nuxt:server-devonly:transform',
@ -29,7 +30,11 @@ export const DevOnlyPlugin = createUnplugin((options: DevOnlyPluginOptions) => {
const s = new MagicString(code)
const strippedCode = stripLiteral(code)
for (const match of strippedCode.matchAll(DEVONLY_COMP_RE) || []) {
s.overwrite(match.index!, match.index! + match[0].length, match.groups?.fallback || '')
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 replacement = fallback ? match[0].slice(fallback.loc[0].end, fallback.loc[fallback.loc.length - 1].start) : ''
s.overwrite(match.index!, match.index! + match[0].length, replacement)
}
if (s.hasChanged()) {

View File

@ -435,6 +435,9 @@ importers:
ufo:
specifier: ^1.1.2
version: 1.1.2
ultrahtml:
specifier: ^1.2.0
version: 1.2.0
unctx:
specifier: ^2.3.0
version: 2.3.0
@ -8277,6 +8280,10 @@ packages:
/ufo@1.1.2:
resolution: {integrity: sha512-TrY6DsjTQQgyS3E3dBaOXf0TpPD8u9FVrVYmKVegJuFw51n/YB9XPt+U6ydzFG5ZIN7+DIjPbNmXoBj9esYhgQ==}
/ultrahtml@1.2.0:
resolution: {integrity: sha512-vxZM2yNvajRmCj/SknRYGNXk2tqiy6kRNvZjJLaleG3zJbSh/aNkOqD1/CVzypw8tyHyhpzYuwQgMMhUB4ZVNQ==}
dev: false
/unbox-primitive@1.0.2:
resolution: {integrity: sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==}
dependencies: