sasseleventy

How to make Eleventy correctly build SCSS while in --serve mode?


I have a simple Eleventy project that uses SCSS.

My file structure is like this:

src
├─ styles
│  ├─ components
│  │  ├─ _buttons.scss
│  │  ├─ _forms.scss
│  ├─ site.scss 

When I run the --serve CLI option the initial build correctly generates a the _site/styles/site.css file. If I make a change to components/*.scss,the CLI notifies me that a watched file was changed but the generated site.css is not changed at all.

However if I make a change directly to the site.scss file or stop the --serve process and re-start it, only then will it correctly generate the correct CSS.

Here is my eleventy.js file

const sass = require('sass');
const path = require('node:path');

module.exports = function (eleventyConfig) {
  eleventyConfig.addTemplateFormats('scss');
  eleventyConfig.addExtension('scss', {
    outputFileExtension: 'css',
    compile: async function (inputContent, inputPath) {
      let parsedPath = path.parse(inputPath);

      let result = sass.compileString(inputContent, {
        loadPaths: [parsedPath.dir || '.', this.config.dir.includes],
      });

      return async (data) => result.css;
    },
  });

  return {
    dir: { input: 'src' },
  };
};

What do I need to change to make this always generate correct CSS?


Solution

  • Eleventy documentation again comes to your rescue. :)

    You need to add one line inside your compile function, before the return:

    this.addDependencies(inputPath, result.loadedUrls);
    

    The result.loadedUrls is the list of imported files - reported by the SASS compiler. With this addDependencies call you pass this list to Eleventy, telling it to watch those files as well, and when they change, rebuild the current file.