MadLittleMods / postcss-css-variables

PostCSS plugin to transform CSS Custom Properties(CSS variables) syntax into a static representation
https://madlittlemods.github.io/postcss-css-variables/playground/
Other
536 stars 62 forks source link

Import variables from js module #63

Closed arahansen closed 6 years ago

arahansen commented 6 years ago

Currently, the plugin supports defining "default" variables in the config as a plain javascript object.

Is there any way to similarly import values from a javascript module?

The syntax I had in mind was something like this:

// variables.json
{
  blue: '#0366d6'
}

// styles.css
@import 'variables.json';

.foo {
  color: var(--blue);
}

my use case is that I would like to reuse these values between javascript and css without duplicating values.

If this is not currently supported, I'd be happy to take a look at adding support.

MadLittleMods commented 6 years ago

@arahansen You can already do this,

var fs = require('fs');
var postcss = require('postcss');
var cssvariables = require('postcss-css-variables');
var myVariables = require('./variables.json');

var mycss = fs.readFileSync('input.css', 'utf8');

// Process your CSS with postcss-css-variables
var output = postcss([
        cssvariables({
            variables: myVariables
        })
    ])
    .process(mycss)
    .css;

console.log(output);

If you actually wanted the @import syntax, it seems like it would be a separate PostCSS plugin that ran before postcss-css-variables and expanded the JSON file into a :root rule with the variables inside.