-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstyle-inject.ts
52 lines (48 loc) · 1.57 KB
/
style-inject.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
/*
* @Description:
* @Autor: wxy
* @Date: 2022-08-12 10:08:37
* @LastEditors: wxy
* @LastEditTime: 2022-08-12 10:17:23
*/
import type { Plugin } from 'vite';
function VitePluginStyleInject(styleId = ''): Plugin {
let styleCode = '';
return {
name: 'vite-plugin-style-inject',
apply: 'build',
enforce: 'post',
generateBundle(_, bundle, isWrite) {
console.log(bundle);
for (const key in bundle) {
if (bundle[key]) {
const chunk = bundle[key];
if (chunk.type === 'asset' && chunk.fileName.includes('.css')) {
styleCode += chunk.source;
delete bundle[key];
}
}
}
for (const key in bundle) {
if (bundle[key]) {
const chunk = bundle[key];
if (chunk.type === 'chunk' &&
chunk.fileName.match(/.[cm]?js$/) !== null &&
!chunk.fileName.includes('polyfill')
) {
const initialCode = chunk.code;
chunk.code = '(function(){ try {var elementStyle = document.createElement(\'style\'); elementStyle.appendChild(document.createTextNode(';
chunk.code += JSON.stringify(styleCode.trim());
chunk.code += ')); ';
if (styleId.length > 0)
chunk.code += ` elementStyle.id = "${styleId}"; `;
chunk.code += 'document.head.appendChild(elementStyle);} catch(e) {console.error(\'vite-plugin-css-injected-by-js\', e);} })();';
chunk.code += initialCode;
break;
}
}
}
},
};
}
export default VitePluginStyleInject;