2

I wonder if there is a way I can share my color variables in css-modules to my js (React) components?

If not, how would you do it? Have two files with color variables?

Thanks!

Kalnode
  • 9,386
  • 3
  • 34
  • 62
Sanne Wintrén
  • 359
  • 1
  • 4
  • 12
  • In SCSS, you'd do like that https://stackoverflow.com/q/57536228/8186898 probably webpack with some plugin allow you to use the same syntax in CSS? – Nino Filiu Feb 16 '21 at 14:45

1 Answers1

1

CSS doesn't have the concept of variables like Sass does, so I'll assume you're referring to CSS custom properties, which a lot of people refer to as "CSS variables".

These custom properties are just that - custom style properties than are set to particular elements and that can be accessed at runtime by JS through getComputedStyle + getPropertyValue. Here's an example:

const root = document.documentElement;
const div = document.querySelector('div');
const x = document.getElementById('x');

const get = (elt, key) => getComputedStyle(elt).getPropertyValue(key);

console.log(
  get(root, '--foo'), // 'Foo!'
  get(div, '--bar'), // 'Bar!'
  get(x, '--baz'), // 'Baz!'
  get(x, '--foo'), // 'Foo!' because properties cascade down
)
:root {
  --foo: 'Foo!';
}
div {
  --bar: 'Bar!';
}
#x {
  --baz: 'Baz!';
}
<div></div>
<div id="x"></div>

As far as I know, there is no official way to export values from CSS files in a way similar to what you'd do in ESM (eg export const mainColor = '#ff0000';).

Sass however supports that, the syntax is as follow and requires a proper support from the sass processor you're using:

// colors.scss
:export {
  main-color: #ff0000;
}
import colors from './colors.scss';
console.log(colors['main-color']); // '#ff0000'
Nino Filiu
  • 16,660
  • 11
  • 54
  • 84
  • Ok, I'm using variables in CSS-modules, like you can se here https://github.com/css-modules/css-modules/blob/master/docs/values-variables.md And it's these variables/values I'm asking if I can use in JS/(react) somehow :) Maybe I have the wrong terminology or something? I have always called them variables :) – Sanne Wintrén Feb 17 '21 at 13:36