How to Have Valid JavaScript Template Files for Eleventy

If the front matter data is not valid syntax in JavaScript, our tools can struggle and therefore, cannot help us code… Fortunately for us, there is a way to fix that!

2 min read
How to Have Valid JavaScript Template Files for Eleventy
Photo by Markus Spiske from Pexels

When I began to combine Web Components with Eleventy as a proof of concept, I quickly realized that I would need to generate JavaScript files from the same language template file, like transforming a *.js.njk file to *.js file.

At first, it seems to be easy, as Eleventy can write any file with the permalink key in the template’s front matter:

---
permalink: /javascript.js
---
The header of our *.js.njk file

But the front matter syntax is not valid JavaScript, so most code editors will mark it as a combination of errors and warnings, as IntelliJ IDEA did to my file:

The same code from above in IntelliJ IDEA

Also, JavaScript linters and formatters, like ESLint and Prettier, will neither recognize that special syntax… We could remove them from our files, but do we want to code without them? Personally, I cannot! 😟

But what if we could replace the --- --- delimiters with others that would be valid JavaScript, as the comment /*--- ---*/? 🧐

Fortunately for us, Eleventy uses the gray-matter npm package for parsing front matter with its default options AND it provides a function to allow us to override these options! To do that, we only need to add a couple of lines to our Eleventy configuration file:

  eleventyConfig.setFrontMatterParsingOptions({
    delimiters: ['/*---', '---*/'],
  });
Except for a .eleventy.js file that overrides front matter parsing

With that configuration, we can now code the front matter data with our new syntax:

/*---
permalink: /javascript.js
---*/

Now our file contains valid JavaScript and our tools will parse it correctly. 😌

Sadly, this approach has a little inconvenience that I learned to live with it: you can specify only one couple of delimiters. So now, you need to use our new syntax everywhere, like in HTML files, even if it is not an appropriate syntax in another language... 😢

So, if you still want to change the default delimiters, I suggest that you look for the greater number of files that you develop and choose the right delimiters for these files. 💡

Do you have any additional tips to develop JavaScript files from Eleventy?