-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathvite.wdnCriticalCSSInjector.js
More file actions
33 lines (29 loc) · 1.21 KB
/
vite.wdnCriticalCSSInjector.js
File metadata and controls
33 lines (29 loc) · 1.21 KB
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
import { existsSync, readFileSync, writeFileSync } from 'fs';
import path from 'path';
export default function wdnCriticalCSSInjector({ cssFile, targets }) {
return {
name: 'WDN: Critical CSS Injector',
apply: 'build',
enforce: 'post',
async closeBundle() {
const cssPath = path.resolve(cssFile);
if (!existsSync(cssPath)) {
console.warn(`CSS file not found: ${cssPath}`);
return;
}
const css = readFileSync(cssPath, 'utf-8');
const wrappedCss = `<style id="unl-critical-css">${css}</style>`;
targets.forEach(targetFile => {
const targetPath = path.resolve(targetFile);
if (!existsSync(targetPath)) {
console.warn(`Target file not found: ${targetPath}`);
return;
}
const criticalCssRegex = new RegExp('<style id="unl-critical-css">[^<]*</style>');
const content = readFileSync(targetPath, 'utf-8');
const updated = content.replace(criticalCssRegex, wrappedCss);
writeFileSync(targetPath, updated, 'utf-8');
});
},
};
}