Description
Tagged template literals are commonly used by web components libraries. They can also include CSS code, HTML code and embedded expressions (a.k.a. substitutions).
ES provides its own:
- semantics (
//...
and/* ... */
) for instructing parser to ignore strings referred ascomment
, and - tagged template literals
The problem
ES parser fails to recognize and, hence, parse correctly (ie to ignore) its own comments within its own tagged template literals.
Example
I wish to de-activate a part of the code within html
tagged template for testing purpose; which means I just don't want to display that part. The first thing that passes from my mind is to use the corresponding html comment semantics.
js-type-file.js
html`
<!--
<p>${v}</p>
<p>Backtick(`)</p>
-->
`
In that case, ES parser:
- gives error when
v
is either defined or not, or - terminates the template earlier due to the first backtick (`) and parser gives an error due to the wrong syntax of the remaining code.
Therefore, ES parser gives priority to its features - expression (${v}
) and backtick (`
) - against HTML features (<!-- ... -->
comment).
Based on that, one can very reasonably assume that adding ES comment semantics will solve the problem. Namely:
html`
<!--
/*
<p>${v}</p>
<p>Backtick(`)</p>
*/
-->
`
Now, unfortunately, ES parser, again, ignores the comment semantics and parses the content resulting in errors.
The same problem exists with CSS syntax, although both CSS and ES use the same comment semantics (/* ... */
) .
Rough ideas how to solve
- Make ES parser to globally ignore ES comment semantics, either
- by using the existing semantics, or
- by adopting new ones, statically parsed, only for use within tagged templates literals (e.g.
<!--/* ... */-->
for HTML,/*/* ... */*/
for CSS, etc)
Parser can do that in the same way that tracks expressions (${...}
) or backtick (`
)
- Make ES parser to consider basic features of other languages (I suspect that it's very "expensive"!)
Caveat
Expressions evaluation may not take place.
html`
/* This is what I want<br>
<p>${v}</p>
<p>Backtick(`)</p>
to display */
`
ES parser will ignore the whole text between the semantics and display:
/* This is what I want
${v}
Backtick(`)
to display */
Although it is not what one can expect, the behavior is totally justified and the outcome makes sense without contradictions.
BUT, with a very small change one can solve even this minor itch. Instead of /*
, one can write /*
. ES parser will not complain at all.
html`
/* This is what I want<br>
<p>${v}</p>
<p>Backtick(\`)</p>
to display */
`
So, the outcome will be something like:
/* This is what I want
It's evaluated!
Backtick(`)
to display */
By that way, ES does not abuse any HTML or CSS feature and goes BY THE BOOK!