Autoload SASS in React using Vite

Arun Bohra
2 min readNov 23, 2022

--

SCSS with React

While using SASS with react you might have a problem that you need to import a partial file (maybe for variables) all the time like the following.

@import './variables.scss';

Well, in this article we’re going to see how to solve that problem and make react to autoload the file.

1. Create a new react app using Vite

First of all, let’s create a new react application using Vite. Follow the below commands in order to do so

npm init vite
# select the react variation
cd vite-project
npm install
Create Vite app

2. Installing and using the sass package

Next, install the “sass” package by running

npm install sass

Now let’s create a sass file and import it in our App.jsx. For this article I’ll just convert “App.css” to “App.scss”.

Also let’s now create the variables partial file and add some variables in there and I’ll name it “_variables.scss”. At the end it should look something like this

// _variables.scss file

$color-1: green;
$color-2: red;

3. Configuring the Vite application

Now we’ll use the variables from “_variables.scss”. In order to do so, we can import the variable files in the “App.scss” like following:

@import './variables';

But we don’t want to keep on doing that all the time. Therefore, we need some configuration that will autoload the file. To do this, we go to “vite.config.js” file and add the following block of code to the object inside defineConfig

css: {
preprocessorOptions: {
scss: {
additionalData: '@import "path-to-variables-file";',
},
},
}

You can read more about this in the docs here.

Once you have done this your “vite.config.json” should look something like this:

vite.config.json file

And now, if you try to add variables to your “App.scss” file, you will be able to see that it is actually able to use variables defined in the variables file.

Conclusion

Although it seems nice to autoload all variables at once, but remember that it may sometimes download some unnecessary files (files that are not needed right away but will be used in future). But still if you need to do something like this now you know how to do it.

--

--