How to get SCSS variables into react

UPDATE: The original answer claims that it is only supported by webpack, but this is no longer true. Many bundlers now support this via their own css processing pipeline.

Original Answer:
That’s a webpack/css-loader feature and only works with webpack and css-loader (https://webpack.js.org/loaders/css-loader/#separating-interoperable-css-only-and-css-module-features)

Important: the :export syntax in your SCSS/CSS files will only work for those files that are treated as a module by css-loader, because this syntax is part of a css module proposal.
You can…

  • either use the default behavior of css-loader and trigger that behavior via filename: e.g. foostyle.module.scss
  • or you can configure css-loader to treat all files as modules e.g. loader: 'css-loader', options: { modules: true }

A blogpost with an example can be found here: https://til.hashrocket.com/posts/sxbrscjuqu-share-scss-variables-with-javascript
(Be aware that the blogpost doesn’t mention the fact that css modules must be used.)

$white-color: #fcf5ed;

:export {
  whitecolor: $white-color;
}

and

import variables from 'variables.module.scss';

console.log(variables.whitecolor)

your webpack.config.js will probably contain a chain of loaders with css-loader as last or second-to-last (process-chronologically speaking) and this should work.

module: {
    rules: [
      {
        test: /\.scss$/,
        use: [ 'style-loader', 'css-loader', 'sass-loader' ],
      },

Leave a Comment