This repository has been archived by the owner on Nov 15, 2024. It is now read-only.
forked from violethaze74/cloudflare-docs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
vite.config.ts
110 lines (106 loc) · 3.09 KB
/
vite.config.ts
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import { fileURLToPath, URL } from "node:url";
import { HTMLRewriter, type ElementHandlers } from "html-rewriter-wasm";
import { defineConfig, type PluginOption } from "vite";
import glob from "glob";
import { highlight } from "./bin/prism.config";
import vue from "@vitejs/plugin-vue";
const encoder = new TextEncoder();
const decoder = new TextDecoder();
async function rewrite(
document: string,
handlers: [string, ElementHandlers][]
) {
let output = "";
const rewriter = new HTMLRewriter((outputChunk) => {
output += decoder.decode(outputChunk);
});
handlers.forEach(([el, handler]) => rewriter.on(el, handler));
try {
await rewriter.write(encoder.encode(document));
await rewriter.end();
return output;
} finally {
rewriter.free();
}
}
const hydrateVueComponents = (): PluginOption => {
return {
name: "hydrate-vue",
transformIndexHtml: {
order: "pre",
handler: async (html: string) => {
let componentId = 1;
return await rewrite(html, [
[
"vue-component",
{
element: (element) => {
const nId = componentId++;
const name = element.getAttribute("name");
element.tagName = "div";
element.removeAttribute("name");
element.setAttribute("id", `vue-c-${nId}`);
element.after(
`<script type="module">
import { createApp } from 'vue'
import Component from "@/${name}.vue"
const root = document.getElementById('vue-c-${nId}')
createApp(Component, {...root.dataset}).mount(root, true)
</script>`,
{ html: true }
);
},
},
],
]);
},
},
};
};
const renderCodeBlock = (): PluginOption => {
return {
name: "render-code-block",
async transformIndexHtml(html: string) {
return await rewrite(html, [
[
"unparsed-codeblock",
{
element: (element) => {
const data = element
.getAttribute("data-code")!
// Hugo's url encoding is ...odd
.replaceAll("+", " ");
if (data.includes("&#")) {
throw new Error("Unexpected HTML entity: " + data);
}
const decoded = decodeURIComponent(data);
const code = decoded + "\n";
element.replace(
highlight(code, element.getAttribute("data-language")!, ""),
{
html: true,
}
);
},
},
],
]);
},
};
};
// https://vitejs.dev/config/
export default defineConfig({
plugins: [renderCodeBlock(), hydrateVueComponents(), vue()],
root: "public",
resolve: {
alias: {
"@": fileURLToPath(new URL("./components", import.meta.url)),
data: fileURLToPath(new URL("./data", import.meta.url)),
},
},
build: {
rollupOptions: {
input: glob.sync("public/**/*.html"),
},
},
});