|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +/** |
| 4 | + * CSS minification script using lightningcss |
| 5 | + * |
| 6 | + * This replaces clean-css which doesn't support modern CSS features |
| 7 | + * like light-dark(), color-mix(), @layer, etc. |
| 8 | + */ |
| 9 | + |
| 10 | +import fs from 'node:fs' |
| 11 | +import path from 'node:path' |
| 12 | +import { transform, browserslistToTargets } from 'lightningcss' |
| 13 | + |
| 14 | +const distDir = path.join(process.cwd(), 'dist/css') |
| 15 | + |
| 16 | +// Get all CSS files that need minification |
| 17 | +const cssFiles = fs.readdirSync(distDir) |
| 18 | + .filter(file => file.endsWith('.css') && !file.endsWith('.min.css')) |
| 19 | + |
| 20 | +// Target browsers (matching Bootstrap's browser support) |
| 21 | +const targets = browserslistToTargets(['> 0.5%', 'last 2 versions', 'Firefox ESR', 'not dead']) |
| 22 | + |
| 23 | +for (const file of cssFiles) { |
| 24 | + const inputPath = path.join(distDir, file) |
| 25 | + const outputPath = path.join(distDir, file.replace('.css', '.min.css')) |
| 26 | + const mapPath = outputPath + '.map' |
| 27 | + |
| 28 | + console.log(`Minifying ${file}...`) |
| 29 | + |
| 30 | + const inputCss = fs.readFileSync(inputPath, 'utf8') |
| 31 | + const inputMap = fs.existsSync(inputPath + '.map') |
| 32 | + ? JSON.parse(fs.readFileSync(inputPath + '.map', 'utf8')) |
| 33 | + : undefined |
| 34 | + |
| 35 | + try { |
| 36 | + const result = transform({ |
| 37 | + filename: file, |
| 38 | + code: Buffer.from(inputCss), |
| 39 | + minify: true, |
| 40 | + sourceMap: true, |
| 41 | + inputSourceMap: inputMap ? JSON.stringify(inputMap) : undefined, |
| 42 | + targets |
| 43 | + }) |
| 44 | + |
| 45 | + // Write minified CSS with source map reference |
| 46 | + const minifiedCss = result.code.toString() + `\n/*# sourceMappingURL=${path.basename(mapPath)} */` |
| 47 | + fs.writeFileSync(outputPath, minifiedCss) |
| 48 | + |
| 49 | + // Write source map |
| 50 | + if (result.map) { |
| 51 | + fs.writeFileSync(mapPath, result.map.toString()) |
| 52 | + } |
| 53 | + |
| 54 | + console.log(` ✓ ${file} → ${path.basename(outputPath)}`) |
| 55 | + } catch (error) { |
| 56 | + console.error(` ✗ Error minifying ${file}:`, error.message) |
| 57 | + process.exit(1) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +console.log('\nCSS minification complete!') |
0 commit comments