【问题标题】:Is it possible to configure prettier to treat text within a script tag as HTML?是否可以配置 prettier 以将脚本标记中的文本视为 HTML?
【发布时间】:2020-05-12 01:11:30
【问题描述】:

我正在使用 Vue,我在脚本标签中编写了许多模板。我想将 Prettier 配置为将这些模板视为 HTML,但我在文档中没有找到有关如何执行此操作的任何内容。

看起来像这样。现在,Prettier 并没有帮助我处理该脚本标签内的 HTML。我想告诉它这些包含 HTML,因此它的行为就像该 HTML 在脚本标记之外一样。

<script type="text/x-template">
  <p>Hello world.</p>
</script>

除此之外...我非常依赖 Prettier,以至于我将 HTML 部分放在脚本标签中,以便它可以放在 Prettier 将在其上运行的单独文件中。令人费解,但这是一种解决方法。不过,我真的想要一个解决方案。

【问题讨论】:

    标签: vue.js prettier


    【解决方案1】:

    另一种方法是使用&lt;template&gt; tags 而不是&lt;script type="text/x-template"&gt;

    <template id="my-component-template">
      <p>Hello world.</p>
    </template>
    

    浏览器不会呈现 &lt;template&gt; 标签,但 Prettier 会识别并将其格式化为常规 HTML。

    这不应与 &lt;template&gt; 标签通常用于在 Vue 指令中包装多个元素(v-ifv-for)相混淆。事实上,您可以将两者混合使用:

    <template id="my-component-template">
      <div class="my-component">
        <template v-if="sayHello">
          <div>Hello</div>
          <div>world!</div>
        </template>
        <div v-else>Good bye</div>
      </div>
    </template>
    

    最外层的&lt;template&gt; 用作Vue 模板的容器,而最内层的&lt;template&gt; 用作控制流

    (顺便说一下,这类似于Single File Components 的组织方式。)

    注意事项

    浏览器会将&lt;template&gt; 标记的内容解析为常规HTML 标记,并尝试纠正“坏”HTML。所以这个:

    <template id="my-component-template">
      <table>
        <another-component></another-component>
      </table>
    </template>
    

    ...将“更正”为:

    <template id="my-component-template">
      <another-component></another-component>
      <table></table>
    </template>
    

    有关详细信息,请查看官方 Vue 文档中的DOM Template Parsing Caveats(或v2 docs)。

    【讨论】:

      【解决方案2】:

      Prettier 目前不支持此功能,但如果有人制作 PR,将来可能会支持。您现在可以做的最接近的事情是使用type="text/x-handlebars-template",但这不会使用与 HTML 相同的解析器和打印机。 Handlebars (Glimmer) 支持仍然是 alpha。

      【讨论】:

        猜你喜欢
        • 2015-06-16
        • 2010-10-29
        • 1970-01-01
        • 1970-01-01
        • 2014-04-21
        • 1970-01-01
        • 1970-01-01
        • 2021-05-05
        • 1970-01-01
        相关资源
        最近更新 更多