Ryan Jones

Sharing Variables with Sass in Jekyll

On a little light work, I was looking for optimizations to the site. Probably premature, as it usually is, however it is fun to try. One way to do this was splitting up css files into multiple parts, only as needed, as per Google recommendations. I did this with my scss files, but then ran into compilation issues due to missing variables. Looking up the docs for Sass, I could not use @use. This meant going further back to @import.

I knew there were a few steps involved.

  1. Break out scss files into smaller ones
  2. Put variables into their own file
  3. Import variables into scss files that required them
  4. Validate change and update site

I checked my settings for sass in the _config.yaml and realized I had set my directory incorrectly, so I am amazed that it all worked in the first place.

sass:
  sass_dir: assets/css
  style: compressed

Put all my scss fles in that assets/css file, and broke out all the variables (they start with a $) into their own file named assets/css/vars.css. The trick here is that this file should not be published or processed by the Jekyll intake, so it _does not need the yaml front matter to get it processed. This will leave it raw for the Sass parser to pick up and include.

As mentioned previously, it cannot use the @use, so down the chain is @import. Since they are all in the same folder, the path is easy, under the yaml front matter in the .scss files that need them: @import 'vars'; which will find the vars.css file in the same directory, still there because it was not processed.

Hope this helps someone make your CSS efficient for page load times 😉