|
1 | 1 | import MarkdownIt from 'markdown-it'
|
2 | 2 | import matter from 'gray-matter'
|
3 |
| -import { toArray } from '@antfu/utils' |
| 3 | +import { toArray, uniq } from '@antfu/utils' |
4 | 4 | import type { ResolvedOptions } from './types'
|
5 | 5 |
|
6 |
| -const scriptSetupRE = /<\s*script[^>]*\bsetup\b[^>]*>([\s\S]*)<\/script>/mg |
| 6 | +const scriptSetupRE = /<\s*script([^>]*)\bsetup\b([^>]*)>([\s\S]*)<\/script>/mg |
7 | 7 | const defineExposeRE = /defineExpose\s*\(/mg
|
8 | 8 |
|
| 9 | +interface ScriptMeta { |
| 10 | + code: string |
| 11 | + attr: string |
| 12 | +} |
| 13 | + |
9 | 14 | function extractScriptSetup(html: string) {
|
10 |
| - const scripts: string[] = [] |
11 |
| - html = html.replace(scriptSetupRE, (_, script) => { |
12 |
| - scripts.push(script) |
| 15 | + const scripts: ScriptMeta[] = [] |
| 16 | + html = html.replace(scriptSetupRE, (_, attr1, attr2, code) => { |
| 17 | + scripts.push({ |
| 18 | + code, |
| 19 | + attr: `${attr1} ${attr2}`.trim(), |
| 20 | + }) |
13 | 21 | return ''
|
14 | 22 | })
|
15 | 23 |
|
@@ -127,13 +135,34 @@ export function createMarkdown(options: ResolvedOptions) {
|
127 | 135 | scriptLines.push('defineExpose({ excerpt })')
|
128 | 136 | }
|
129 | 137 |
|
130 |
| - scriptLines.push(...hoistScripts.scripts) |
| 138 | + scriptLines.push(...hoistScripts.scripts.map(i => i.code)) |
131 | 139 |
|
132 |
| - const scripts = isVue2 |
133 |
| - ? `<script>\n${scriptLines.join('\n')}\n${frontmatterExportsLines.join('\n')}\n${excerptExportsLine}export default { data() { return { frontmatter } } }\n</script>` |
134 |
| - : `<script setup>\n${scriptLines.join('\n')}\n</script>${frontmatterExportsLines.length ? `\n<script>\n${frontmatterExportsLines.join('\n')}\n</script>` : ''}${excerptExportsLine !== '' ? `\n<script>\n${excerptExportsLine}</script>` : ''}` |
| 140 | + const attrs = uniq(hoistScripts.scripts.map(i => i.attr)).join(' ') |
135 | 141 |
|
136 |
| - const sfc = `<template>${html}</template>\n${scripts}\n${customBlocks.blocks.join('\n')}\n` |
| 142 | + const scripts = isVue2 |
| 143 | + ? [ |
| 144 | + `<script ${attrs}>`, |
| 145 | + ...scriptLines, |
| 146 | + ...frontmatterExportsLines, |
| 147 | + excerptExportsLine, |
| 148 | + 'export default { data() { return { frontmatter } } }', |
| 149 | + '</script>', |
| 150 | + ] |
| 151 | + : [ |
| 152 | + `<script setup ${attrs}>`, |
| 153 | + ...scriptLines, |
| 154 | + '</script>', |
| 155 | + ...((frontmatterExportsLines.length || excerptExportsLine) |
| 156 | + ? [ |
| 157 | + `<script ${attrs}>`, |
| 158 | + ...frontmatterExportsLines, |
| 159 | + excerptExportsLine, |
| 160 | + '</script>', |
| 161 | + ] |
| 162 | + : []), |
| 163 | + ] |
| 164 | + |
| 165 | + const sfc = `<template>${html}</template>\n${scripts.join('\n')}\n${customBlocks.blocks.join('\n')}\n` |
137 | 166 |
|
138 | 167 | return sfc
|
139 | 168 | }
|
|
0 commit comments