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

Prettier配置需求:内容长度未超printWidth时不换行

需求:为Prettier新增HTML内联内容换行控制配置

核心需求:添加一项Prettier配置规则,实现当整行代码总长度小于printWidth设定值时,HTML标签内部的内容不换行,具体场景及预期如下:

场景案例

案例1:行长度超出printWidth(符合当前行为,无需修改)

输入:

<div b={2} a={2} b={3} c={22}>s</div>

当前输出(符合预期):

<div b={2} a={2} b={3} c={22}>
        s
</div>

说明:整行总长度超过printWidth,标签内内容换行是合理的格式化行为。

案例2:空标签(符合当前行为,无需修改)

输入:

<div b={2} a={2} b={3} c={22}></div>

当前输出(符合预期):保持单行,无内部内容时无需换行。

案例3:行长度小于printWidth(需要修正行为)

输入:

<div b={2} a={2}>a</div>

当前输出:

<div b={2} a={2}>
a
</div>

期望输出:

<div b={2} a={2}>a</div>

说明:整行总长度明显小于printWidth,应强制保持单行,避免不必要的换行。

实现方案:自定义Prettier插件

由于Prettier默认没有内置该配置项,可通过自定义插件实现逻辑判断:

插件代码示例

// prettier-plugin-html-inline-content.js
const prettier = require("prettier");
const { parsers: htmlParsers } = require("prettier/plugins/html");

function processHtmlElement(path, options) {
  const node = path.getValue();
  if (node.type !== "element") return;

  // 计算整行代码的总长度(标签+属性+内容+闭合标签)
  const openingTagLen = node.openingTag.source.length;
  const closingTagLen = node.closingTag ? node.closingTag.source.length : 0;
  const contentLen = node.children.reduce((sum, child) => {
    return sum + (child.source ? child.source.length : 0);
  }, 0);
  const totalLineLen = openingTagLen + contentLen + closingTagLen;

  // 总长度小于printWidth时,强制内容与标签同行
  if (totalLineLen < options.printWidth && node.children.length > 0) {
    // 清理文本节点的换行和缩进
    path.eachChild(childPath => {
      if (childPath.getValue().type === "text") {
        const trimmedText = childPath.getValue().source.trim();
        childPath.replace({ ...childPath.getValue(), source: trimmedText });
      }
    });
    // 确保标签与内容无换行间隔
    node.openingTag.source = node.openingTag.source.trimEnd();
    if (node.closingTag) node.closingTag.source = node.closingTag.source.trimStart();
  }
}

module.exports = {
  parsers: {
    html: {
      ...htmlParsers.html,
      format: (ast, options) => {
        prettier.astTraverse(ast, { element: processHtmlElement });
        return htmlParsers.html.format(ast, options);
      }
    }
  }
};

使用方法

  1. 将上述代码保存为项目根目录下的prettier-plugin-html-inline-content.js
  2. 在Prettier配置文件中引入插件:
// prettier.config.js
module.exports = {
  printWidth: 80, // 可根据项目需求调整
  plugins: ["./prettier-plugin-html-inline-content.js"]
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 04:32:07