You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Prettier保留Svelte中script标签的自闭合写法

解决Prettier修改Svelte自闭合script标签的问题

你遇到的是Prettier默认格式化规则导致的问题——它不把script标签视为可自闭合的元素,因此会自动将自闭合的<script ... />补全为完整的闭合标签。有两种可行的解决方式:

方式一:修改Prettier全局配置

在你的Prettier配置文件(比如.prettierrc、prettier.config.js)中,自定义html.selfClosingTags相关规则,把script加入允许自闭合的元素列表:

如果用JSON格式的配置文件:

{
  "html": {
    "selfClosingTags": true,
    "voids": ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr", "script"]
  }
}

如果用JS格式的配置文件:

module.exports = {
  html: {
    selfClosingTags: true,
    voids: [...require("prettier").htmlVoidElements, "script"]
  }
}

这样配置后,Prettier会保留script标签的自闭合写法。

方式二:局部忽略格式化

如果只想针对单个标签跳过Prettier的格式化,直接在标签上方添加<!-- prettier-ignore -->注释即可:

<!-- prettier-ignore -->
<script src="..." on:load={() => console.log('!')} />

内容的提问来源于stack exchange,提问作者opensas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 16:40:19