TSX 组件样式标签中 CSS 的语法突出显示

Syntax Highlighting for CSS in a Style Tag in a TSX Component

在我的 React 应用程序中,我喜欢在给定 TSX 组件的样式标签中编写 CSS 样式。有没有办法在这种情况下实现 CSS 的 VS Code 语法突出显示?

目前,整个文件反映了 TSX 语法高亮显示,这意味着 CSS 字符串片段都是单一颜色。

我没有使用 styled-components

下面是我想在样式标签内容中突出显示的文本示例:

export default function HomeStyle() {
  return (
    <style>{`
    .container {
      min-height: 100vh;
      padding: 0 0.5rem;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    
    .main {
      padding: 5rem 0;
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    
    .footer {
      width: 100%;
      height: 100px;
      border-top: 1px solid #eaeaea;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    `}</style>
  );
}

如果您使用名为 css 的标记模板文字,您应该获得 CSS 智能感知和语法突出显示。例如:

const css = String.raw;
 
export default function HomeStyle() {
  return (
    <style>{css`
    .container {
      min-height: 100vh;
      padding: 0 0.5rem;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    .main {
      padding: 5rem 0;
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    .footer {
      width: 100%;
      height: 100px;
      border-top: 1px solid #eaeaea;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    `}</style>
  );
}

如果您使用名为 html 的标记模板文字,您应该获得 HTML 智能感知和语法突出显示。例如:

const html = String.raw

const template = html`
  <div class="container"></div>
`

在这些示例中,我使用 String.raw 作为直通。框架可能会提供自己的 htmlcss 函数以用于添加框架特定功能的目的。