Skip to content
This repository has been archived by the owner on Mar 6, 2020. It is now read-only.

Export CSS output to JSON #470

Open
rrmesquita opened this issue Feb 28, 2020 · 1 comment
Open

Export CSS output to JSON #470

rrmesquita opened this issue Feb 28, 2020 · 1 comment

Comments

@rrmesquita
Copy link

Hi!

Is there a way to export CSS output to JSON? It would work like so:

CSS Output:

.mb\:12: {
    margin-bottom: 1.5rem;
}

.mb\:16: {
    margin-bottom: 2rem;
}

JSON Output:

{
    "mb:12": "margin-bottom: 1.5rem;",
    "mb:16": "margin-bottom: 2rem;",
}

I'm developing an autocomplete plugin for IntelliJ IDEs, and that would be really helpful for me and also other people developing around Tailwind. I appreciate any tip you can give me.

Thanks!

@cytRasch
Copy link

cytRasch commented Mar 3, 2020

Try something like this:

const encoding = 'utf8'
const fs = require( 'fs' )
const css = require( 'css' )
const path = require( 'path' )
const parse = ( code, file ) => css.parse( code, { source: file } )

let classNames = [],
    styles

/**
 *  transform css to json
 *
 * @param file
 * @param output
 * @param cb
 * @returns {any} AST object
 */
const cssToJson = function ( file, output, cb ) {

    // resolve file path
    const abs = path.resolve( file )

    // parse css code from file
    const flow = code => parse( code, file )

    // return AST object
    return typeof cb == 'function' ? fs.readFile( abs, encoding, function ( err, code ) {
        err ? cb( err ) : cb( err, flow( code ) )
    } ) : flow( fs.readFileSync( abs, encoding ) )
}

// destrcut object
const { stylesheet } = cssToJson( './node_modules/tailwindcss/dist/utilities.css' );

for ( styles of stylesheet.rules ) {

    let { selectors, declarations } = styles,
        properties = ''

    // sometimes declarations and/or selectors
    // are undefined.
    // make more tests to get the why
    if ( declarations && selectors ) {
        Object.entries( declarations ).forEach( ( [key, val] ) => {

            properties += `${val.property}:${val.value};`
        } )

        // replace backslashes
        selectors = selectors[ 0 ].replace( /\\/gm, '' );

        classNames[ selectors ] = properties
    }

}

console.log( classNames )

This gives you all the css stuff in a json file. Play with it, you'll get the idea.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants