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!
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'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.