-
-
Save alvivi/4297e6232d55db1fb62671a060519b8b to your computer and use it in GitHub Desktop.
A little tool to convert css to elm-css Snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that it requires
reworkcss/css
as dependency.