One of the most annoying things when working on the frontend, is that sometime you have to handle in JavaScript information you have already available in your styles.

Up until today, I was totally unaware that you can import the sass variables in JavaScript and I stubbornly duplicated the values.

Today I have been forwarded this css tricks article which completely blew me away!

A very short pratical example (but I suggest you to read it).

Provided that you use sass-loader in your webpack configuration, you just need to add an :export block with the variables declared and import the sass file in your JavaScript file.

If you write a SCSS file like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// variables.scss
$bp-size-small: 420;
$bp-size-medium: 768;
$bp-size-large: 1024;

:export {
  bpSizeSmall: $bp-size-small;
  bpSizeMedium: $bp-size-medium;
  bpSizeLarge: $bp-size-large;
}

You can write something like this 😱:

1
2
3
import variables from './variables.scss';

const isDesktop = window.innerWidth > variables.bpSizeMedium;

PS

For even cleaner approach to breakpoints, you can use something like this strip-unit mixin to rewrite the scss file like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// variables.scss
$bp-size-small: 420px;
$bp-size-medium: 768px;
$bp-size-large: 1024px;

:export {
  bpSizeSmall: strip-unit($bp-size-small);
  bpSizeMedium: strip-unit($bp-size-medium);
  bpSizeLarge: strip-unit($bp-size-large);
}

to actually reuse the same values in sass and javascript.