Skip to content

Commit

Permalink
✨ Generate css from JS variables
Browse files Browse the repository at this point in the history
  • Loading branch information
cprodhomme authored and jpolo committed Nov 5, 2024
1 parent a243b63 commit 0d1dc24
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/cherry-sea/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
],
"scripts": {
"build": "npx run-p \"build:*\"",
"build-css-vars": "tsc && node dist/generate-css-vars.js",
"build:tsc": "tsc -b tsconfig.build.json",
"clean": "npx run-p \"clean:*\"",
"clean:tsc": "rm -rf dist",
Expand Down
35 changes: 35 additions & 0 deletions packages/cherry-sea/src/generate-css-vars.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/* eslint-disable no-console */
import fs from 'node:fs';
import { colors, fonts, spacing } from './index.js';

function toCSSVariables(obj: object, prefix = ''): string {
let cssVars = '';

// Utilise Object.entries pour itérer uniquement sur les propriétés propres de l'objet
Object.entries(obj).forEach(([key, value]) => {
if (typeof value === 'object' && !Array.isArray(value)) {
// Appel récursif pour les objets imbriqués
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
cssVars += toCSSVariables(value, `${prefix}-${key}`);
} else {
// Formate le nom de la variable CSS
const cssVarName = `${prefix}-${key}`.replaceAll('_', '-').toLowerCase();
cssVars += ` --${cssVarName}: ${Array.isArray(value) ? value.join(',') : value};\n`;
}
});

return cssVars;
}

function generateCSSFile(variables: object, dist: string) {
const cssVariables = `:root {\n${toCSSVariables(variables, '')}}\n`;

fs.writeFile(dist, cssVariables, (err) => {
if (err != null) throw err;
console.log(`Le fichier CSS a été généré avec succès : ${dist}`);
});
}

generateCSSFile(colors, 'dist/colors.css');
generateCSSFile(fonts, 'dist/fonts.css');
generateCSSFile(spacing, 'dist/spacing.css');

0 comments on commit 0d1dc24

Please sign in to comment.