Sass support in Eleventy

Enabling the Eleventy build process to handle Sass stylesheets isn't too difficult, but I couldn't find one place that documented all the moving pieces you need in your Eleventy config for (what I consider) a production-ready implementation.

import path from "node:path";
import * as sass from "sass";

export default async function (eleventyConfig) {
  // [...] other configuration here

  eleventyConfig.addTemplateFormats("scss");

  // Tell Eleventy to treat .scss as a template file
  eleventyConfig.addExtension("scss", {
    outputFileExtension: "css",

    // `compile` is called once per .scss file in the input directory
    compile: async function (inputContent, inputPath) {
      const parsed = path.parse(inputPath);

      // skip partials
      if (parsed.name.startsWith("_")) {
        return;
      }

      const result = sass.compileString(inputContent, {
        loadPaths: [
          parsed.dir ?? ".",
          "./src/assets/theming", // <- customize for your site structure
        ],
        sourceMap: false,
        style: "compressed",
      });

      this.addDependencies(inputPath, result.loadedUrls);

      // This is the render function, `data` is the full data cascade
      return async (data) => {
        return result.css;
      };
    },
  });
}