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

如何在浏览器中使用Prettier美化并高亮XML语法?

在浏览器中用Prettier格式化XML的方法

Prettier核心包自带的插件不包含XML支持,你提到的prettier/plugin-xml是第三方插件,无需打包工具即可在浏览器中直接使用,只需加载该插件的UMD构建版本,具体实现如下:

完整代码示例

<script src="https://unpkg.com/prettier@3.2.5/standalone.js"></script>
<script src="https://unpkg.com/@prettier/plugin-xml@3.4.0/dist/standalone.js"></script>
<script>
  (async () => {
    // 待格式化的XML内容
    const rawXml = `<root><name>test</name><description>sample xml content</description></root>`;
    const formattedXml = await prettier.format(rawXml, {
      parser: "xml",
      plugins: [prettierPlugins.xml],
      // 可选配置:自定义格式化规则
      tabWidth: 2,
      xmlWhitespaceSensitivity: "ignore"
    });
    console.log(formattedXml);
    // 可将结果渲染到页面
    // document.getElementById('result').textContent = formattedXml;
  })();
</script>

关键说明

  • 插件版本需与Prettier核心版本兼容,示例中@prettier/plugin-xml@3.4.0和prettier@3.2.5为兼容组合
  • 插件加载后会挂载到prettierPlugins.xml,需在配置的plugins数组中明确指定
  • 可根据需求添加XML专属配置项,比如xmlWhitespaceSensitivity用于控制空白处理逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 20:42:34