/** * Writes `.br` and `.gz` copies of the text assets next to the built files. * * The server serves those directly when a browser offers an encoding, so no * request ever pays for compression: `index-*.js` is ~780 kB raw and ~240 kB * gzipped, which is the difference between a slow and a normal first load. * Images and fonts are already compressed and are left alone. */ import fs from 'node:fs'; import fsp from 'node:fs/promises'; import path from 'node:path'; import zlib from 'node:zlib'; import { fileURLToPath } from 'node:url'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const DIST = path.join(ROOT, 'dist'); const MIN_BYTES = 1024; const COMPRESSIBLE = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.json', '.map', '.txt', '.xml', '.webmanifest']); const brotliOptions = { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 11, [zlib.constants.BROTLI_PARAM_SIZE_HINT]: 0, }, }; async function* walk(dir) { for (const entry of await fsp.readdir(dir, { withFileTypes: true })) { const full = path.join(dir, entry.name); if (entry.isDirectory()) yield* walk(full); else if (entry.isFile()) yield full; } } function isStale(source, target) { try { const out = fs.statSync(target); return out.mtimeMs < fs.statSync(source).mtimeMs; } catch { return true; } } async function compressFile(file, totals) { const ext = path.extname(file).toLowerCase(); if (!COMPRESSIBLE.has(ext)) return 0; const stat = await fsp.stat(file); if (stat.size < MIN_BYTES) return 0; const raw = await fsp.readFile(file); let files = 0; for (const variant of ['gz', 'br']) { const target = `${file}.${variant}`; if (!isStale(file, target)) continue; const body = variant === 'gz' ? zlib.gzipSync(raw, { level: 9 }) : zlib.brotliCompressSync(raw, { ...brotliOptions, params: { ...brotliOptions.params, [zlib.constants.BROTLI_PARAM_SIZE_HINT]: raw.length, }, }); // A "compressed" file that is larger than the original is never served. if (body.length >= raw.length) { await fsp.rm(target, { force: true }); continue; } await fsp.writeFile(target, body); files += 1; totals[variant] += raw.length - body.length; } return files; } if (!fs.existsSync(DIST)) { console.error('precompress: dist/ is missing — run "vite build" first'); process.exit(1); } const totals = { gz: 0, br: 0 }; let files = 0; for await (const file of walk(DIST)) { files += await compressFile(file, totals); } const kb = (bytes) => `${Math.round(bytes / 1024)} kB`; console.log( `precompress: wrote ${files} variant(s); a full load saves ${kb(totals.gz)} with gzip or ${kb(totals.br)} with brotli`, );