Contents

vscode ES6 template literal HTML亮字提示

在 VSCode 中撰寫 JavaScript 時,如果在 Template Literal(模板字面值)裡嵌入 HTML 字串,預設不會有語法高亮或 IntelliSense 提示,閱讀起來相當辛苦。這篇記錄幾個解決方案。

問題說明

Template Literal 是 ES6 引入的字串語法,使用反引號(`)包住字串,支援多行與插值。在以下情況中,裡面的 HTML 沒有語法高亮:

1
2
3
4
5
6
const template = `
  <div class="card">
    <h2>${title}</h2>
    <p>${content}</p>
  </div>
`;

VSCode 把整個字串當成純文字,沒有顏色區分,也不會提示 HTML 標籤或屬性。

解決方案一:es6-string-html(推薦)

安裝 es6-string-html 擴充套件後,只要在反引號前加上 /*html*/ 註解,VSCode 就會以 HTML 語法來高亮整段字串:

1
2
3
4
5
6
const template = /*html*/`
  <div class="card">
    <h2>${title}</h2>
    <p>${content}</p>
  </div>
`;

安裝方式:在 VSCode 擴充功能搜尋 es6-string-html,或執行:

1
code --install-extension Tobermory.es6-string-html

這個套件同樣支援 CSS、SQL、Markdown 等語言的 template literal 高亮:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const styles = /*css*/`
  .card {
    background: white;
    border-radius: 8px;
  }
`;

const query = /*sql*/`
  SELECT id, name FROM users WHERE active = 1
`;

解決方案二:lit-html

如果使用 lit-htmlLitElement 框架,直接使用 html tagged template literal:

1
2
3
4
5
6
7
8
import { html } from 'lit';

const template = html`
  <div class="card">
    <h2>${title}</h2>
    <p>${content}</p>
  </div>
`;

安裝 lit-plugin VSCode 擴充套件後,html tag 的模板字串就會有完整的 HTML 語法支援,包含:

  • 語法高亮
  • 標籤與屬性自動完成
  • Hover 提示文件
  • 錯誤診斷
1
code --install-extension runem.lit-plugin

解決方案三:Inline HTML

Inline HTML 擴充套件支援多種 tag 名稱觸發 HTML 高亮,包括 htmlrawtemplate 等,不需要安裝特定框架:

1
2
3
4
// 以下這些 tag 都會觸發 HTML 高亮
const t1 = html`<div>${content}</div>`;
const t2 = template`<div>${content}</div>`;
const t3 = raw`<div>${content}</div>`;

各方案比較

套件 觸發方式 適用場景
es6-string-html /*html*/ 註解 一般 Vanilla JS,最輕量
lit-plugin html tag 使用 LitElement 框架
Inline HTML 多種 tag 名稱 一般用途,彈性較高

實際應用場景

這個功能在以下情況特別有用:

  1. Vanilla JS 不使用框架:直接操作 DOM,用 template literal 組裝 HTML
  2. Web ComponentscustomElements.define 搭配 template literal
  3. Server-Side Rendering:Node.js 後端產生 HTML 字串
  4. 電子郵件模板:在 JS 中撰寫 HTML 郵件內容