This commit is contained in:
40
scripts/critical-css.js
Normal file
40
scripts/critical-css.js
Normal file
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Inline critical CSS into built HTML using Beasties.
|
||||
* Run after vite build; reads/writes build/.
|
||||
*/
|
||||
import { readFileSync, writeFileSync, readdirSync } from 'fs';
|
||||
import { join, dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import Beasties from 'beasties';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const buildDir = join(__dirname, '..', 'build');
|
||||
|
||||
function getFiles(dir, ext, files = []) {
|
||||
for (const name of readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, name.name);
|
||||
if (name.isDirectory()) getFiles(full, ext, files);
|
||||
else if (name.name.endsWith(ext)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
const beasties = new Beasties({
|
||||
path: buildDir,
|
||||
preload: 'default',
|
||||
logLevel: 'warn'
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const htmlFiles = getFiles(buildDir, '.html');
|
||||
for (const htmlFile of htmlFiles) {
|
||||
const html = readFileSync(htmlFile, 'utf8');
|
||||
const inlined = await beasties.process(html);
|
||||
writeFileSync(htmlFile, inlined);
|
||||
}
|
||||
console.log('Critical CSS inlined:', htmlFiles.length, 'file(s)');
|
||||
}
|
||||
main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in New Issue
Block a user