12

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

Trevor Reid
  • 3,310
  • 4
  • 27
  • 46
ravinggenius
  • 816
  • 1
  • 6
  • 14

3 Answers3

5

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";
alienlebarge
  • 3,008
  • 5
  • 24
  • 26
1

A few options I know of:

  • Both postcss-simple-vars and postcss-custom-properties allow you to pass in variables from JavaScript instead of having to define them in CSS files -- meaning that they'd be accessible everywhere.

  • Concatenate your files, putting the variables at the top, before compiling with PostCSS. Or use postcss-imports to handle this for you.

Trevor Reid
  • 3,310
  • 4
  • 27
  • 46
davidtheclark
  • 4,666
  • 6
  • 32
  • 42
0

I really don't understand what you are trying to accomplish, or what you mean by global variables. The point of variables is to access them across your CSS files. They will not be compiled into your CSS anyway so why not just store all your variables in a file called global.css and reference the variables wherever you need by importing the global file.

SCSS is just a preprocessor so none of your variables are actually written to the CSS file therefore you needn't worry about scoping of variables.

TheEarlyMan
  • 384
  • 4
  • 15