-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite-plugin-html-partials.js
More file actions
49 lines (43 loc) · 1.81 KB
/
vite-plugin-html-partials.js
File metadata and controls
49 lines (43 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// vite-plugin-html-partials.js
// ─────────────────────────────────────────────────────────────────
// Replaces <!-- include:name --> markers in index.html with the
// contents of src/partials/name.html — at both dev-server and build time.
//
// Usage in index.html:
// <!-- include:toolbar -->
// <!-- include:sidebar -->
// etc.
// ─────────────────────────────────────────────────────────────────
import { readFileSync } from 'fs'
import { resolve } from 'path'
export default function htmlPartials(partialsDir = 'src/partials') {
const MARKER = /<!--\s*include:(\S+?)\s*-->/g
function inject(html, root) {
return html.replace(MARKER, (_, name) => {
const file = resolve(root, partialsDir, `${name}.html`)
try {
return readFileSync(file, 'utf-8')
} catch {
console.warn(`[html-partials] Missing partial: ${file}`)
return `<!-- partial "${name}" not found -->`
}
})
}
return {
name: 'html-partials',
// Dev server — transform index.html on every request
transformIndexHtml(html, ctx) {
const root = ctx.server?.config?.root ?? process.cwd()
return inject(html, root)
},
// Build — transform the bundled HTML
generateBundle() {},
transformIndexHtml: {
order: 'pre',
handler(html, ctx) {
const root = ctx.server?.config?.root ?? process.cwd()
return inject(html, root)
}
}
}
}