Search code examples
javascriptcsscss-modulescss-parsingglamorous

Parse CSS into JavaScript with selector awareness


I want to build something that could consume a .css file return a function that would take an array of class names and return the styles that would apply to an element with those class names, as a JavaScript object. (Such an tool would be suitable for use with Glamor, Fela, or other CSS-in-JS technologies.)

E.g., if you have this CSS file:

.btn {
  border: 1px solid gray;
}

.btn.primary {
  background: blue;
  border-color: blue;
}

.btn-group {
  display: inline-block;
}

then you could do something like this:

import css from "./btn.css";
import applicableStyles from "applicable-styles"; // what I want to build

const btnStyles = applicableStyles(css, ['btn', 'primary']);

// Expected value:
{
  border: "1px solid gray"
  background: "blue";
  border-color: "blue";
}

In this example, .btn-group gets ignored because we only asked what style would apply to .btn.primary.

This is new territory for me, but I know there are tools out there for parsing CSS. What libraries might be most promising to take a look at? (Or, does something like this exist already?)


Solution

  • This should be possible using some of the various npm packages out there.

    For example, the css-object-loader package allows you to require a .css file, which is converted to an object with keys corresponding to the selectors, which you can then access.

    p {
      font-size: 14px;
    }
    
    h1 {
      text-indent: 20px;
    }
    
    .centered {
      width: 100%;
      margin: 0 auto;
    }
    
    var selectors = require('./rules.css');
    
    // Get the 
    selectors['.centered']
    

    I've also seen SCSS destructured at import, like:

    import {btn, primary} from './btn.scss';
    

    but unfortunately I can't remember what loaders were used to do this.