Using global SASS variables in React component

Viewed 5078

Each import of SCSS file in JS file is treated as an isolated SASS env, therefore, there is no such thing "global variables" while using SCSS in React. This behavior requires us to import the variables.scss file into each SCSS file that uses one of the variables.

_variables.scss

$global-font : "Cairo", sans-serif;
$global-background: whitesmoke;

App.js

import './App.scss'

export function App()
{
    return (
        <div className="App"></div>
    )
}

App.scss

@import "variables.scss";

.App {
    background-color: $global-background;
    font-family: $global-font;
    // ...
}

Header.js

import './Header.scss'

export function Header()
{
    return (
        <div className="Header"></div>
    )
}

Header.scss

@import "variables.scss";

.Header {
    background-color: $global-background;
    font-family: $global-font;
    // ...
}

I have to import the _variables.scss file to multiple (maybe 100+) other SCSS files to make use of the variables. Does doing this increase bundle size?

P.S. The variables.scss file contains only SCSS variables and nothing else.

2 Answers

It shouldn't-- unused variables will simply be removed from the compiled SCSS. From the Sass Variables docs:

Sass variables are all compiled away by Sass.

You can experiment with this on an Online Sass Playground-- open the filesystem UI, add a bunch of unused variables to the _variables.scss, then save, close the filesystem and convert/compile the output-- you'll see that used variables simply have the value replaced where they are used, and unused variables are "compiled away".

If its just variables then it won't bloat the output but if your imported files are doing more than that, then it might increase your build output, as per SCSS docs

with @import Each stylesheet is executed and its CSS emitted every time it’s @imported, which increases compilation time and produces bloated output.

I'd suggest using css variables for your globals. Simply declare them once in your main stylesheet that is loaded on entry


:root {
  --var-one: something;
  --var-two: something;
}

and use them anywhere,

  // in stylesheets
  .someclass {
     ...
     font-size: var(--var-one);
   }

   //or even in jsx
   
   <component style={{fontSize: 'var(--var-one)'}} />
Related