Skip to content

Instantly share code, notes, and snippets.

@ArturJS
Created June 8, 2025 17:52
Show Gist options
  • Select an option

  • Save ArturJS/30119f93f3e13cdc8b986cdb7607a39a to your computer and use it in GitHub Desktop.

Select an option

Save ArturJS/30119f93f3e13cdc8b986cdb7607a39a to your computer and use it in GitHub Desktop.
CSS colors extractor
import * as fs from 'fs';
import * as path from 'path';
const cssDir = 'src';
const outputFile = 'src/vars.css';
const hexRegex = /#([a-fA-F0-9]{3,6})/g;
const rgbRegex = /rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)/g;
const rgbaRegex = /rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*\d*\.?\d+\s*\)/g;
const colorMap = new Map();
function scanDir(dir) {
fs.readdirSync(dir).forEach(file => {
const fullPath = path.join(dir, file);
if (fs.statSync(fullPath).isDirectory()) {
scanDir(fullPath);
} else if (file.endsWith('.css')) {
extractColors(fullPath);
}
});
}
function extractColors(file) {
const content = fs.readFileSync(file, 'utf8');
[...content.matchAll(hexRegex), ...content.matchAll(rgbRegex), ...content.matchAll(rgbaRegex)]
.forEach(match => colorMap.set(match[0], `--rj-${match[0].replace(/[^a-fA-F0-9,]/g, '')}`));
}
scanDir(cssDir);
const cssVars = [...colorMap.entries()]
.map(([color, varName]) => `${varName}: ${color};`)
.join('\n');
fs.writeFileSync(outputFile, `:root {\n${cssVars}\n}\n`);
console.log(`CSS variables file created: ${outputFile}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment