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

5
  • are you looking for developer.mozilla.org/en/docs/Web/API/Window/getComputedStyle ? Just connect CSS file in an iframe, create the elements there and get their styles Commented Sep 22, 2017 at 16:23
  • Perhaps developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet might help . . . Commented Sep 22, 2017 at 16:34
  • I don't want getComputedStyle — that returns a huge list of computed properties. Commented Sep 22, 2017 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 Commented Sep 22, 2017 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. :/ Commented Sep 22, 2017 at 20:35

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.