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

Variables Declaration Replaced #24

Closed oleersoy closed 8 years ago

oleersoy commented 8 years ago

Hi,

I have a CSS file like this:

@import 'cssB.css';

:root {
  --varA: var(--varB);
}

h1 {
  color: var(--varA);
}

And in cssB.css:

:root {
  --varB: 'valueB';
}

If I run this through the following script:

var postcss = require('postcss');
var cssvariables = require('postcss-css-variables');
var importCSS = require('postcss-import');

var fs = require('fs');

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

// Process your CSS with postcss-css-variables
var output = postcss([
  cssvariables( /*options*/ )
]).use(importCSS)
  .process(mycss)
  .css;

console.log(output);

I get this as a result:

:root {
  --varB: 'valueB';
}

h1 {
  color: undefined;
}

So the original cssA.css :root selector is replaced by the :root selector from cssB.css. Is that supposed to happen? Since suitcss theme uses multiple :root selectors in a single file, I assumed that this was OK?

I tried changing cssA.css to look like this:


/*
@import 'cssB.css';
*/

:root {
  --varB: 'valueB';
}

:root {
  --varA: var(--varB);
}

h1 {
  color: var(--varA);
}

When I run process.js I now get this as a result:

/*
@import 'cssB.css';
*/

h1 {
  color: 'valueB';
}

So it works with multiple :root selectors in the same file, although they are not removed once the variables are resolved.

I did one more experiment. It looks like this:

@import 'cssB.css';

:root {
  --varB: 'valueB';
}

:root {
  --varA: var(--varB);
}

h1 {
  color: var(--varA);
}

In this case the result is:

ole@MKI:~/Sandbox/test1$ node process.js 
:root {
  --varB: 'valueB';
}

h1 {
  color: 'valueB';
}

So the @import statement only replaces the first root selector...

Ole

MadLittleMods commented 8 years ago

This is as expected. You need to run postcss-import before postcss-css-variables to get desired results.

var output = postcss([
    importCSS(),
    cssvariables( /*options*/ )
  ])
  .process(mycss)
  .css;

Which will make your original example look like the following when it reaches postcss-css-variables

:root {
  --varB: 'valueB';
}

:root {
  --varA: var(--varB);
}

h1 {
  color: var(--varA);
}
oleersoy commented 8 years ago

Ah - Super - Thanks!