Use Sass variables in Javascript

Sudhakar Rayavaram
TarkaLabs TIL
Published in
1 min readFeb 24, 2018

Sass is very good to keep your CSS dry by defining variables and use it across all the scss files. But, with React and the concept of css in js, sometimes we need to use these variables like theme colors, default font size in the react components we import. Instead of defining them again, it is better if we can use the same Sass variables so that it is easy to change in one place

ICSS module which is used by css-loader makes it possible

Let us take a file called example.scss which has a couple of variables that needs to be used in javascript. :export block is what does the trick

// example.scss

$primary-color: #55A5C3;
$secondary-color: #DB6B7E;

:export {
primaryColor: $primary-color;
secondarColor: $secondary-color;
}

In javascript, you can import the scss file and use it in the javascript file

import styles from ‘../components/example.scss’

#Use it where you need it
color = styles.primaryColor

--

--

Sudhakar Rayavaram
TarkaLabs TIL

[su-docker] Software plumber, health and wellness enthusiast, digital artist, data visualization lover & …