postcss / postcss-custom-properties

Use Custom Properties in CSS
https://postcss.github.io/postcss-custom-properties
MIT License
596 stars 77 forks source link

Extract computed variables for JavaScript #49

Closed athyuttamre closed 8 years ago

athyuttamre commented 8 years ago

Hi, I'm trying to use this module to create a webpack loader. The goal of the webpack loader is to take in a CSS file containing variables, and output JSON with the variables. Sort of like sass-variables-loader, but for CSS.

Input:

/* colors.css */

:root {
  --myRed: red;
  --myBlue: blue;
  --myPrimary: var(--myBlue)
  --myWidth: 20;
}

Output:

{
  "myRed": "red",
  "myBlue": "blue",
  "myPrimary": "blue",
  "myWidth": 20
}

Is there a way to extract a JavaScript object mapping from variable names to values?

MoOx commented 8 years ago

See preserve and appendVariables options to do this.

athyuttamre commented 8 years ago

Thanks!

For future readers: I ran my CSS through this module with preserve: "computed" as well as postcss-calc to resolve all the variables. Then I used the css npm module to parse through the tree, find :root selectors, and find all declarations inside that started with --.

You can also see an example in https://www.npmjs.com/package/css-variables-loader.

MoOx commented 8 years ago

Why don't you "just" use postcss itself, instead of css module (which is what is used for... rework!).

athyuttamre commented 8 years ago

Haha, fair point. I'm running the CSS through postcss within webpack, but the JSON is being generated in a loader. I want to distribute the loader separately, so the less dependencies there the better. postcss is heavier than just the css module. :)

emattias commented 7 years ago

@athyuttamre How come you didn't use the https://www.npmjs.com/package/css-variables-loader that you linked to? :)