-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
59 lines (52 loc) · 1.98 KB
/
main.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 * as fs from 'fs';
import { resolve } from 'path';
import type { PluginOption, ResolvedConfig } 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 injectStyles(): PluginOption {
return {
name: 'inject-css',
apply: 'build',
configResolved(resolvedConfig: ResolvedConfig) {
viteConfig = resolvedConfig;
},
transform(code: string, id: string) {
if (fileRegex.test(id)) {
css.push(code);
return {
code: '',
};
}
if (id.includes((viteConfig.build.lib as any).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)) {
data = data.replace(template, injectCode(css.join('\n')));
}
fs.writeFileSync(filePath, data);
} catch (e) {
console.error(e);
}
}
},
};
}