Updating 11ty to enjoy ESM

Post #7 published on by Tobias Fedder

In case you're already using Eleventy (11ty) to generate files for your webserver to distribute, as I do, then you know that 11ty lives in the world of CommonJS (CJS). Or at least it did up to version 2. With version 3 on the way it is also possible to use ECMAScript modules (ESM).

To make that change I ran npm i -D @11ty/eleventy@canary --save-exact. As the term canary might suggest, it doesn't install the current stable version, but the 3.0.0-alpha.5 (at time of writing). Hence it is important to set the --save-exact flag, that's what Zach Leatherman the creator of 11ty said in his talk at TheJam.dev 2024 anyway. It's about changing 11ty's code from CJS to ESM for the most part, and quite informative at that.

Switching from CJS to ESM can be done in steps, you don't have to migrate everything at once. There are different ways to switch as well, documented at this 11ty blog post.

I don't have a lot of JS files yet so I decided to switch everything in one go. First, I added "type": "module" to my package.json file. Second, I replaced the CJS syntax in my eleventy.config.js with the ESM syntax.

const fs = require("fs")
const zlib = require("zlib")

const eleventyNavigationPlugin = require("@11ty/eleventy-navigation")
const eleventyRssPlugin = require("@11ty/eleventy-plugin-rss")
const htmlMinifier = require("html-minifier")

module.exports = function(conf) {
import fs from "fs"
import zlib from "zlib"

import eleventyNavigationPlugin from "@11ty/eleventy-navigation"
import eleventyRssPlugin from "@11ty/eleventy-plugin-rss"
import htmlMinifier from "html-minifier"

export default function(conf) {

Then I did the same for the two data files and one test file I have. Like I said, not a lot of files. That's all I needed to do to switch to ESM.

Pretty neat, because — despite being a web developer — the amount of JS I have to write at my job is (worryingly?) low. Sure, some components need JS for the UI, so I write a few lines from time to time. But running JS on the server isn't a thing at my job. Okay, we use JS to build frontend resources, but we rarely need to touch these build tools. That's why my experience, regarding JS APIs that interact with the operating system or modules to organize and reuse JS, is somewhat limited. Now that I push myself to becoming a bit more familiar with it, through building this website, I prefer to focus on the standard that works in browsers as well. That is ESM.
Thank you Zach, for making the migration a breeze.