Import Sass variables in JavaScript with Webpack

Wouldn't that be great?

We can define the entire theme in Sass files and then when we need to have them in our JavaScript, we can use them without having to redeclare them in a JSON?

First, let's create a Sass file with a bunch of variables. Generally it would ideally be the file where we define all our variables related to the project.

For simplicity, let's say we are dealing with colors and want all the theme colors to be made available in JavaScript.

// colors.scss

/*=============================================
=            Black, White, Grays            =
=============================================*/

$--color-black: #000000;
$--color-charcoal: #212121;
$--color-abstract: #5c5c5c;
$--color-slate: #737373;
$--color-earth: #ababab;
$--color-edge: #e7e7e7;
$--color-mercury: #f0f0f0;
$--color-seashell: #f7f6f5;
$--color-fairy: #f7f7f7;
$--color-white: #ffffff;

/*=====  End of Black, White, Grays  ======*/

Now, to have the exact same thing exported we are going to use Webpack's magic export from the Sass file itself, which looks like this.

:export {
  black: $--color-black;
  charcoal: $--color-charcoal;
  abstract: $--color-abstract;
  slate: $--color-slate;
  earth: $--color-earth;
  edge: $--color-edge;
  mercury: $--color-mercury;
  seashell: $--color-seashell;
  fairy: $--color-fairy;
  white: $--color-white;
}

Lastly, we can simply import the colors.scss file in JavaScript and use the colors.

import colors from "colors.scss";

console.log(colors.black); // #000000

That's it! Ain't that great?

Hope that helps!