1

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?)

Alan H.
  • 16,219
  • 17
  • 80
  • 113
  • are you looking for https://developer.mozilla.org/en/docs/Web/API/Window/getComputedStyle ? Just connect CSS file in an iframe, create the elements there and get their styles – smnbbrv Sep 22 '17 at 16:23
  • Perhaps https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet might help . . . – Alan Larimer Sep 22 '17 at 16:34
  • I don't want getComputedStyle — that returns a huge list of computed properties. – Alan H. Sep 22 '17 at 20:31
  • CSSStyleSheet however is a very interesting API and may be of use, although I was hoping to do this in Node without a browser environment – Alan H. Sep 22 '17 at 20:32
  • hmm on second thought, CSSRule only seems to offer the `CSSRule.cssText` property to get at the rule — it doesn’t even separate the selector from the style properties, much less represent them in JavaScript format. :/ – Alan H. Sep 22 '17 at 20:35

1 Answers1

1

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.

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184