Export SASS/SCSS variables to Javascript without exporting them to CSS

Note: I have posted this answer because it seems there is no better solution, however, if someone subsequently provides a better solution, I will be more than happy to accept it.

It seems that the only real solution to this is to extract the export statement out of the _variables.scss file and place it into its own _export.scss file which will subsequently not be included in the SCSS compliation.

This will look something like this:

_variables.scss – included in the SCSS compilation

/* Define all colours */
$white:    #fff;
$black:    #000;
$grey:     #ccc;
// etc...

_export.scssnot included in the SCSS compilation

@import "variables";

:export {

    // Export the color palette to make it accessible to JS
    white: #fff;
    black: #000;
    grey: #ccc;
    // etc...

}

And then your app.scss (I use brand.scss) file will look something like this (note the absence of @include "export";):

@import "variables";
@import "mixins";
@import "core";
@import "animations";
// etc...

Then, _export.scss is simply referenced only in JavaScript like so (note that core-styles is just an alias that I used in my projects):

import styles from 'core-styles/brand/_export.scss';

Leave a Comment

tech