user2355058
user2355058

Reputation: 221

Import variables into css module in React

I use CSS modules and my css/stylesheet files live next to my components.

What is the fastest way to support a global colors file that can be imported into my stylesheet?

Does my css-modules and webpack support this by default? Help.

Upvotes: 1

Views: 6580

Answers (1)

NTP
NTP

Reputation: 399

Are you using CRA? If so, you can. You just have to make sure that you are using postcss and the postcss-modules-values plugin. NOTE: Haven't tested this without Create React App (yet), so if anyone has, it would help to know.

Now, all you need is create a stylesheet (or simply use the index.css, your choice), and do this:

@value blue: #0c77f8;
@value red: #ff0000;
@value green: #aaf200;

And now, from your component-scoped css file, just import and use (almost JS-like):

/* import your colors... */
@value colors: "./colors.css";
@value blue, red, green from colors;

.button {
  color: blue;
  display: inline-block;
}

Source(docs).

Upvotes: 4

Related Questions