DEV Community

Pacharapol Withayasakpunt
Pacharapol Withayasakpunt

Posted on

Fake tagged template string literal to enable syntax highlighting in VSCode

This is as simple as

const lit = (s: TemplateStringsArray, ...args: any[]) => s.map((ss, i) => `${ss}${args[i] || ''}`).join('')

const css = lit  // Which also with inline-css, not only real *.css files
const html = lit
const pug = lit
const sql = lit
Enter fullscreen mode Exit fullscreen mode

Now this works,

sql`SELECT name FROM sqlite_master WHERE type='table'`
Enter fullscreen mode Exit fullscreen mode

Required VSCode extensions

For HTML and Pug, it seems to work without a plugin.

Why?

Before then, I don't notice that there are so many reserved keywords in SQLite, and I ran to trouble sometimes. This can be escaped with "...".

Tagged template literal identify a possible keyword, which maybe unsafe, so it is better. (Not sure which SQL dialect does it mean, though.)

sql`SELECT "name" FROM sqlite_master WHERE type='table'`
Enter fullscreen mode Exit fullscreen mode

Other kinds of escaping

For HTML and Pug, I believe you can try https://www.npmjs.com/search?q=html%20entities

At the current point of time, I am not sure why you need lit-html.

Top comments (3)

Collapse
 
trusktr profile image
Joe Pea

What about js?

js`if (true) foo`

doesn't seem to be supported. Do you know a good plugin for that? (useful to send code to a web worker for example).

Collapse
 
iamarsenibragimov profile image
Arsen Ibragimov

Could you please explain what this line of code means?

const lit = (s: TemplateStringsArray, ...args: any[]) => s.map((ss, i) => ${ss}${args[i] || ''}).join('')

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

It's literally what template string tags are -- functions.

You have to try this in your console.

function foo(...args) {
  console.log(JSON.stringify(args))
}

foo`a${1}b${2}c${3}d`

I get

[["a","b","c","d"],1,2,3]

The first arg is always an array of strings, and the latter args are objects, in their native form.