-
Notifications
You must be signed in to change notification settings - Fork 6
/
vite.svelte.config.ts
84 lines (69 loc) · 2.32 KB
/
vite.svelte.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
import { PluginOption, defineConfig } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { JSDOM } from "jsdom";
export function generateUI(): PluginOption {
return {
name: "generateUI",
config: undefined,
enforce: "post",
generateBundle: (_, bundle) => {
console.log("");
let jsFileName: string | undefined;
let jsSrc: string | undefined;
let cssFileName: string | undefined;
let cssSrc: string | undefined;
for (const [k, v] of Object.entries(bundle)) {
if (k.endsWith(".js") && v.type === "chunk") {
console.log("JS:", v.fileName);
jsFileName = v.fileName;
jsSrc = v.code;
delete bundle[k];
}
if (k.endsWith(".css") && v.type === "asset") {
console.log("CSS:", v.fileName);
cssFileName = v.fileName;
cssSrc = `${v.source}`;
delete bundle[k];
}
}
if (!jsFileName || !jsSrc) {
throw new Error("Input JS file not found");
}
if (!cssFileName || !cssSrc) {
throw new Error("Input CSS file not found");
}
for (const [k, v] of Object.entries(bundle)) {
if (k.endsWith(".html") && v.type === "asset") {
console.log("HTML:", v.fileName);
const dom = new JSDOM(v.source);
const doc = dom.window.document;
const jsElem = doc.querySelector(`script[src*="${jsFileName}"]`);
if (!jsElem) {
throw new Error("Input HTML file does not contain a script tag");
}
jsElem.remove();
const jsElemNew = doc.createElement("script");
jsElemNew.innerHTML = jsSrc;
doc.body.appendChild(jsElemNew);
const cssElem = doc.querySelector(`link[href*="${cssFileName}"]`);
if (!cssElem) {
throw new Error("Input HTML file does not contain a script tag");
}
cssElem.remove();
const cssElemNew = doc.createElement("style");
cssElemNew.innerHTML = cssSrc;
doc.head.appendChild(cssElemNew);
v.source = dom.serialize();
}
}
console.log("Bundled JS and CSS into HTML file");
},
};
}
// https://vitejs.dev/config/
export default defineConfig({
build: {
emptyOutDir: false,
},
plugins: [svelte(), generateUI()],
});