DEV Community

Cover image for How to have valid JavaScript template files for Eleventy
Benjamin Rancourt
Benjamin Rancourt

Posted on • Originally published at benjaminrancourt.ca on

How to have valid JavaScript template files for Eleventy

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
--------
Enter fullscreen mode Exit fullscreen mode
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 , like 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, like a comment /*--- ---*/? 🧐

Fortunately for us, Eleventy uses the gray-matternpm 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: ['/*---', '---*/'],
  });
Enter fullscreen mode Exit fullscreen mode
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
--------*/
Enter fullscreen mode Exit fullscreen mode

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

Sadly, this approach has a little inconvenient 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 to choose the right delimiters for these files. 💡

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

Top comments (0)