Skip to content

Instantly share code, notes, and snippets.

@alvivi
Created February 28, 2018 08:41
Show Gist options
  • Save alvivi/4297e6232d55db1fb62671a060519b8b to your computer and use it in GitHub Desktop.
Save alvivi/4297e6232d55db1fb62671a060519b8b to your computer and use it in GitHub Desktop.
A little tool to convert css to elm-css Snippets
#!/usr/bin/env node
const fs = require("fs");
const parse = require("css").parse;
const path = require("path");
if (process.argv.length !== 3) {
const exec = path.basename(process.argv[1]);
console.log(`usage ./${exec} input.css`);
console.log("converts css to elm-css snippets");
process.exit(-1);
}
const inputFilename = process.argv[2];
const inputData = fs.readFileSync(inputFilename);
const css = parse(inputData.toString()).stylesheet;
const snippets = css.rules
.filter(rule => rule.selectors && rule.type === "rule")
.map(rule => {
const props = rule.declarations
.filter(decl => decl.type === "declaration")
.map(decl => `property "${decl.property}" "${decl.value}"`);
return [
`selector "${replaceAll(rule.selectors.join(", "), '"', '\\"')}"`,
` [ ${props.join("\n , ")}`,
" ]"
].join("\n");
});
const moduleName = capitalize(path.basename(inputFilename, ".css"));
const source = [
`module ${moduleName} exposing (snippets)`,
"",
"import Css exposing (property)",
"import Css.Foreign exposing (Snippet, selector)",
"",
"snippets : List Snippet",
"snippets =",
` [ ${snippets.join("\n , ")}`,
" ]"
].join("\n");
console.log(source);
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function replaceAll(source, pattern, replacement) {
return source.replace(new RegExp(pattern, "g"), replacement);
}
@alvivi
Copy link
Author

alvivi commented Feb 28, 2018

Note that it requires reworkcss/css as dependency.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment