Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

CSS-modules are a great way to organize and modularize CSS, and they can also be used to define variables. Here's how you can utilize these variables within JavaScript:

  1. Declare your CSS variables in a .css file with the :root selector:
:root {
  --primary-color: blue;
  --secondary-color: red;
  --font-size: 16px;
}
  1. Import your CSS file into your JS module using import statement:
import styles from './styles.css'; // import CSS-modules

Note: It's important to ensure your CSS file is imported with a .css extension, and that you have set up webpack to handle these imports.

  1. Access your CSS variables from the styles object:
console.log(styles['--primary-color']); 
console.log(styles['--secondary-color']); 
console.log(styles['--font-size']);

This will print the value of the CSS variables onto the console.

  1. Use your CSS variables in your JS module:
document.body.style.backgroundColor = styles['--primary-color'];

This will set the background color of the <body> element to the value of the --primary-color variable.

That's it! You can now use your CSS-modules variables directly in your JavaScript, making your code more maintainable and organized.