How to define PostCSS variables in one CSS file to be "imported" into another CSS file?

ravinggenius picture ravinggenius · Jul 24, 2015 · Viewed 8.6k times · Source

In Sass I can define my variables in a separate file _variables.scss, then make those variables available anywhere I use @import variables;. (Actually the variables are globally available after their first import.)

With PostCSS I can use postcss-simple-vars or postcss-css-variables to define variables local to a single file. I'd like to define all/most variables in a single file, then @import that file wherever I need to use them.

I know the PostCSS plugins can have pre-defined variables configured for the plugin, but then I cannot, for example, calculate a contrasting color for a given background.


Edit: I probably wasn't clear about what my question was.

Is there a way to define PostCSS variables in a CSS file such that the variables are not global, but can be "imported" into another CSS file?

As mentioned above, I can use Sass, but then all variables are effectively global (not ideal). Otherwise in PostCSS I can define the variables in each stylesheet I need them (what's the point?), or I can define them in a static JavaScript structure (static in that they can't reference other variables).

Answer

alienlebarge picture alienlebarge · Apr 6, 2016

You can use postcss-import to import files like in Saas.

Then, you create a files with the vars and import them where you like.

@import "css/_variables.css";