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

You can subscribe on YouTube, or consider becoming a patron if you want to support my work.

Patreon
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