-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
59 lines (52 loc) · 1.75 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
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(html: string) {
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;
},
};
}