-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvite-plugin-style-inject.ts
36 lines (34 loc) · 1.07 KB
/
vite-plugin-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
import { PluginOption } from 'vite'
export default function (): PluginOption {
let styleCode = ''
return {
name: 'vite-plugin-style-inject',
apply: 'build',
enforce: 'post',
generateBundle(_, 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$/) &&
!chunk.fileName.includes('polyfill')
) {
const injectStyleCode = `;(function () {var s = document.createElement('style');s.textContent = '${styleCode.trim()}';document.head.appendChild(s)})();`
chunk.code = injectStyleCode + chunk.code
break
}
}
}
}
}
}