Syntax Highlight JavaScript Template Strings

Published Sep 7, 2021

One of my favorite things when working with vanilla JavaScript is using template literals because it makes working with the Document Object Model (DOM) faster and more fun than using the imperative browser API.

Take the output of some movies as example.

example.js
const movies = ['Seven Samurai', 'Hara-Kiri', 'Yojimbo', 'The Sword of Doom']

const ulElement = document.createElement('ul')

for (const movie of movies) {
  const liElement = document.createElement('li')
  liElement.textContent = movie
  ulElement.append(liElement)
}

document.body.append(ulElement)

We didn’t even add classes, attributes, or nested elements yet that make the code harder to read, and more error prone compared to using template literals. I’m not saying you shouldn’t do it — but it sucks the fun out of it.

example.js
const movies = ['Seven Samurai', 'Hara-Kiri', 'Yojimbo', 'The Sword of Doom']

const moviesHtml = `
  <section>
    <h1>Samurai Movies</h1>
    <ul>
      ${movies.map((movie) => `<li>${movie}</li>`).join('')}
    </ul>
  </section>
`

document.body.innerHTML = moviesHtml

It’s not perfect because we don’t get the usual benefits and help from our code editor such as syntax highlight, code completion from IntelliSense and Emmet which causes similar problems I had before.

That’s how I found Inline HTML — a Visual Studio Code extension that solves those problems.

To use it you only have to prefix the template literal with html or /* html */. You can do the same for CSS using css or /* css */.

example.js
const movies = ['Seven Samurai', 'Hara-Kiri', 'Yojimbo', 'The Sword of Doom']

const moviesHtml = /* html */ `
  <section>
    <h1>Samurai Movies</h1>
    <ul>
      ${movies.map((movie) => `<li>${movie}</li>`).join('')}
    </ul>
  </section>
`

document.body.innerHTML = moviesHtml

Conclusion

That’s it! 👏

Enjoy working on your next vanilla JavaScript, or TypeScript project. Use Vite to further enhance your developer experience.

Thanks for reading! 🏄‍♀️

Support

If you want to support the content you're reading or watching on YouTube consider becoming a patreon starting low as 1$ per month.

Become a patreon
Subscribe For Updates
Found a mistake?

Every post is a Markdown file so contributing is simple as following the link below and pressing the pencil icon inside GitHub to edit it.

Edit on GitHub