Using SCSS variables inside your JavaScript, TypeScript or TypeScript JSX files
If you are familiar to SCSS (I guess that’s why you are here) then you already love the fact that you can have variables in SCSS. You can import the SCSS variables inside your style files and use them the way you want to.
“But I want to use these SCSS variables inside my JavaScript / TypeScript / TSX files… Can you tell me how?” Absolutely, I will tell you how to do so in 3 quick-to-do steps. So let’s cut to the chase…
Step 1: We need to have proper webpack config
module.exports = {
module: {
rules: [
{
test: /\.scss$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader"
},
{
loader: "sass-loader"
}
]
}
]
}
};
Step 2: Go to the SCSS file where you have kept your SCSS variables. Add the magical “:export {}” & put all the key:value inside it
$background: #0062ff;
$text: #272d33;
$inverse: #f4f7fb;:export {
background: $background;
text: $text;
inverse: $inverse;
}
Step 3: Import the variables file in your JS/TS/TSX file and use it like any object
import variables from 'src/styles/variables.scss';<YourComponent
color={variables.background}
/>or
<svg>
<line x1={0} y1={0} x2={50} y2={50} stroke={variables.inverse} /></svg>
…and you are ready to rock! 😊
Thanks for reading. Do let me know your feedback below. Follow me on Twitter, Instagram or YouTube.