miguel.nz

How to share variables between SCSS and Javascript

April 5, 2023   |   1 minute read.

One of the most useful features I find while doing front-end development is sharing variables between SCSS and Javascript.

Let’s say we want to share the variable $mainColor between our CSS file and Javascript.

Here is a small tutorial on how to do it:

1. Create a variables.module.scss file

# variables.module.scss

$mainColor: #A9F;

:export {
  mainColor: $mainColor;
}

2. On your scripts.js file

# scripts.js

import variables from 'variables.module.scss';
const { mainColor } = variables;

3. Bonus: You can use these variables on your SCSS files. Let’s say we want to use style.scss

# style.scss

@use 'variables.module' as var;

:root {
  --main-color: #{var.$mainColor}
}

body {
  background-color: var(--main-color);
}

This can also be applied between mediaqueries or other variables you would find relevant.