Bundle CSS files in Jekyll (no external plugins)
Intro
Do you need a plugin for Jekyll to combine multiple SASS/SCSS files into a single bundle CSS file? The answer will be no. I was surprised to find out that Jekyll can do it out of the box without any plugins necessary. Let’s have a look.
In Jekyll it is easy to go from this:
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="/css/base.css">
<link rel="stylesheet" type="text/css" href="/css/first.css">
<link rel="stylesheet" type="text/css" href="/css/second.css">
<link rel="stylesheet" type="text/css" href="/css/third.css">
<link rel="stylesheet" type="text/css" href="/css/final.css">
To this:
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="/css/main.css">
Steps
Explanation
Sass files that are meant to be imported, not compiled on their own, are called partials. By default Jekyll looks for partials sass/scss files in the _sass
folder which is configurable BTW.
We will configure Jekyll to @import
multiple partials into a single file.
1. Place SCSS files into “_sass” folder
Move or place all the sass/scss files that you want to combine into the _sass
folder in the root of your Jekyll website. You will need to create it if it doesn’t exist.
2. Ensure SCSS files are not compiled on their own
In order to do that you need to make sure that there are no ”---
” at the top of the files. Simply delete the “dashes” if they are there. In example, if your file looks like:
---
---
/* example */
.button { ... }
Then after the changes it should look like:
/* example */
.button { ... }
3. Create your bundle file
In my case I created main.scss
and put it into css
folder. Feel free to choose a different name for the file.
Then simply @import
all partials that you want to combine into the final bundle:
---
---
@import "base";
@import "first";
@import "second";
@import "third";
@import "final";
Conclusion
Having fewer CSS files on a website helps it load faster and will result in a better page speed score which is good for SEO. It is always a good idea to bundle multiple css files. Luckily, using Jekyll’s Sass converter it becomes an easy task.
You may take a look at a real world commit to bundle multiple css files into one.