Where CSS preprocessing fits in an Eleventy build

Eleventy ships without an opinionated way to preprocess CSS, and the approaches people take vary widely. Some run Gulp; others use a template that returns preprocessed CSS, or extend the Eleventy config itself to handle the processing. The version that reads most cleanly is a pair of npm scripts: process CSS first, then HTML, chained with npm-run-all.

  "scripts": {
    "build": "npm-run-all build:css build:html",
    "build:css": "node-sass src/site/_includes/css/main.scss > src/site/css/main.css",
    "build:html": "eleventy",
    "watch": "npm-run-all --parallel watch:css watch:html",
    "watch:css": "node-sass --watch src/site/_includes/css/main.scss > src/site/css/main.css",
    "watch:html": "eleventy --serve --port=8181",
    "start": "npm run watch"
  },

Because Eleventy never blessed a CSS pipeline, keeping Sass out of Eleventy's own processing feels appropriate. Netlify's Build Plugins offer another place to put it: the plugin system exposes hooks at fixed points in the build — onPreBuild, onPostBuild, onSuccess — and lets you run logic at each. Plugins come from the community or from Netlify, enabled through the UI or named in config. Sass is not among the built-in plugins, presumably because CSS processing is such an opinionated territory.

Writing an onPreBuild plugin

Set up a directory in the project for plugins, and a folder inside it for this one. The index.js in that folder holds the plugin code and registers an onPreBuild hook, so Sass finishes preprocessing before Eleventy runs and moves files around.

project-root/
  src/
  whatever/
  plugins/
    sass/
      index.js
      manifest.yml
module.exports = {
  onPreBuild: async ({ utils: { run } }) => {
    await run.command(
      "node-sass src/site/_includes/css/main.scss src/site/css/main.css"
    );
  },
};

With all the relevant files in place, running netlify build from the command line reproduces the build Netlify performs itself, including the plugin hook.

One catch: the newer netlify.yml config format did not work with the plugin. Re-doing the config as netlify.toml fixed it. The tradeoff is explicit coupling: CSS processing no longer depends on Eleventy, but it now depends on Netlify.

What the package.json looks like

The split configuration that results is more explicit, and the package.json gets noticeably cleaner:

Removed a bunch of lines from the scripts area of a package.json file, like the specific build:css and build:html commands