Code splitting in SCSS


2 min read

Last post I talked about what code splitting was and how you'd do it, and gave an example with CSS. This post I'm going to talk about how to do it in SCSS.

We're going to stick with our simple website that has three sections: header, main, footer. And we're going to be using a bundler to put all the files into one CSS file.


You can't just write a load of SCSS files and stick them together, you have to write partial files. To do this, you name your file starting with an underscore, eg _header.scss, rather than header.scss. That's it, there's nothing different you need to do inside the file.

Index file

You then need a file that tells it where to find all those partial files you used. This one isn't named with an underscore. You can call this file whatever you like, eg index.scss. Then inside it you have:

@use 'header';
@use 'main';
@use 'footer';

Your files will be called _header.scss, _main.scss, _footer.scss. In your index you don't use the scss or the underscore.

Then the bundler will look at the index file, find the three files you've told it to use, stick them together in one file and convert them to CSS.

More complicated sites

You might have a file with your variables in and another file with your mixins, it gets a little more complicated. I recommend Coder Coder's video - she goes through it all, why it should be done that way and how it works.