Skip to content

Commit

Permalink
refactor: use parser
Browse files Browse the repository at this point in the history
  • Loading branch information
ineshbose committed May 14, 2023
1 parent 9db2f8d commit 340478a
Show file tree
Hide file tree
Showing 3 changed files with 156 additions and 4 deletions.
1 change: 1 addition & 0 deletions packages/nuxt/package.json
Expand Up @@ -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",
Expand Down
7 changes: 5 additions & 2 deletions packages/nuxt/src/core/plugins/dev-only.ts
Expand Up @@ -3,14 +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)>[\s\S]*?<\/(?:dev-only|DevOnly)>/g
const FALLBACK_SLOT_RE = /<template\s+#fallback>(?<fallback>[\s\S]*?)<\/template>/

return {
name: 'nuxt:server-devonly:transform',
Expand All @@ -30,7 +30,10 @@ export const DevOnlyPlugin = createUnplugin((options: DevOnlyPluginOptions) => {
const s = new MagicString(code)
const strippedCode = stripLiteral(code)
for (const match of strippedCode.matchAll(DEVONLY_COMP_RE) || []) {
const replacement = match[0].match(FALLBACK_SLOT_RE)?.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)
}

Expand Down
152 changes: 150 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 340478a

Please sign in to comment.