-
Notifications
You must be signed in to change notification settings - Fork 0
/
libInjectCss.ts
68 lines (59 loc) · 2.19 KB
/
libInjectCss.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
import fs from "fs";
import { resolve } from "path";
import type { ResolvedConfig, PluginOption } from "vite";
const fileRegex = /\.(css)$/;
const injectCode = (code: string) =>
`function styleInject(css,ref){if(ref===void 0){ref={}}var insertAt=ref.insertAt;if(!css||typeof document==="undefined"){return}var head=document.head||document.getElementsByTagName("head")[0];var style=document.createElement("style");style.type="text/css";if(insertAt==="top"){if(head.firstChild){head.insertBefore(style,head.firstChild)}else{head.appendChild(style)}}else{head.appendChild(style)}if(style.styleSheet){style.styleSheet.cssText=css}else{style.appendChild(document.createTextNode(css))}};styleInject(\`${code}\`)`;
const template = `console.warn("__INJECT__")`;
let viteConfig: ResolvedConfig;
const css: string[] = [];
export default function libInjectCss(): PluginOption {
return {
name: "lib-inject-css",
apply: "build",
configResolved(resolvedConfig: ResolvedConfig) {
viteConfig = resolvedConfig;
},
transform(code: string, id: string) {
if (fileRegex.test(id)) {
css.push(code);
return {
code: "",
};
}
if (
// @ts-ignore
id.includes(viteConfig.build.lib.entry)
) {
return {
code: `${code}
${template}`,
};
}
return null;
},
async writeBundle(_: any, bundle: any) {
for (const file of Object.entries(bundle)) {
const { root } = viteConfig;
const outDir: string = viteConfig.build.outDir || "dist";
const fileName: string = file[0];
const filePath: string = resolve(root, outDir, fileName);
try {
let data: string = fs.readFileSync(filePath, {
encoding: "utf8",
});
if (data.includes(template)) {
// search and replace any "`" and replace with "'" to avoid breaking the template string
data = data.replace(
template,
injectCode(css.map((str) => str.replace(/`/g, "'")).join("\n"))
);
}
fs.writeFileSync(filePath, data);
} catch (e) {
console.error(e);
}
}
},
};
}