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.
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.
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 */
.
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! ๐โโ๏ธ