-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
76 lines (63 loc) · 1.94 KB
/
index.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
import path from "path";
import fs from "fs";
import type { Plugin, ResolvedConfig } from "vite";
import type { IHtmlInjectionConfig, IHtmlInjectionConfigInjection } from "./types";
export function htmlInjectionPlugin(
htmlInjectionConfig: IHtmlInjectionConfig,
): Plugin {
let config: undefined | ResolvedConfig;
return {
name: "html-injection",
configResolved(resolvedConfig) {
config = resolvedConfig;
},
transformIndexHtml: {
order: htmlInjectionConfig.order,
handler: (html: string) => transformHtml({ html, config, htmlInjectionConfig }),
},
};
}
type TransformProps = {
html: string;
htmlInjectionConfig: IHtmlInjectionConfig;
config?: ResolvedConfig;
};
function transformHtml({ html, htmlInjectionConfig, config }: TransformProps) {
let out = html;
for (let i = 0; i < htmlInjectionConfig.injections.length; i++) {
const injection: IHtmlInjectionConfigInjection =
htmlInjectionConfig.injections[i];
const root = (config as ResolvedConfig).root;
const filePath = path.resolve(root, injection.path);
let data = fs.readFileSync(filePath, "utf8");
if (
injection.buildModes &&
((injection.buildModes === "dev" && !config?.env.DEV) ||
(injection.buildModes === "prod" && !config?.env.PROD))
) {
continue;
}
if (injection.type === "js") {
data = `<script>\n${data}\n</script>\n`;
} else if (injection.type === "css") {
data = `<style>\n${data}\n</style>\n`;
}
switch (injection.injectTo) {
case "head":
out = out.replace("</head>", `${data}\n</head>`);
break;
case "head-prepend":
out = out.replace(/<head(.*)>/i, `$&\n${data}`);
break;
case "body":
out = out.replace("</body>", `${data}\n</body>`);
break;
case "body-prepend":
out = out.replace(/<body(.*)>/i, `$&\n${data}`);
break;
default:
break;
}
}
return out;
}