sasseleventy

How to exclude files or folder from eleventy?


I am brand new to Eleventy, and generally everything is going smoothly. I have a simple Eleventy project that uses SCSS for my styles. I have a single styles/site.scss file which imports various components from /styles/components/*.scss.

When I build or serve the project it does transform my SCSS files into CSS, but it also builds and copies over everything to /styles/components/*.css which I do not need. These are duplicated bits of code since everyting in them is already included in /styles/components/site.css - this is the only generated CSS file I want to include.

Here's what is generated in the /_site/ folder

Eleventy SCSS file output

Here is my .eleventy.js file

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

module.exports = function (eleventyConfig) {
  eleventyConfig.addPassthroughCopy("src/img");
  eleventyConfig.addPassthroughCopy("src/js");

  eleventyConfig.addTemplateFormats("scss");
  eleventyConfig.addExtension("scss", {
    outputFileExtension: "css",
    compile: function (inputContent, inputPath) {
      let parsedPath = path.parse(inputPath);
      let result = sass.compileString(inputContent, {
        loadPaths: [parsedPath.dir || ".", this.config.dir.includes],
      });

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

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

Solution

  • The magic happens in the compile function inside addExtension("scss", { ... }). This function is called build-time for every *.scss file in your project.

    The function receives the inputPath.

    Try checking whether it's a file in a directory you wish to exclude, and if so, just return from the function (as per documentation). For example:

    if (inputPath.includes('components')) return;