如何配置ESLint/Prettier避免React组件中HTML标签不必要换行?
解决Prettier强制换行JSX内联标签的问题
Prettier会强制将JSX/TSX中所有HTML标签换行,<div>、<main>这类块级标签尚可接受,但<p>、<a>、<span>这类内联标签我希望保留内联格式,仅在内容超过行宽时换行,不改动标签前后空白,由我自行控制格式。目前只能在组件return前临时禁用Prettier,但这种方式扩展性极差。
示例
输入代码
const example = () => { return ( <div><p>This is an example of a long line with <a href="#">links</a> and <span>spans</span>.</p></div> ); }
预期格式化结果
const example = () => { return ( <div> <p>This is an example of a long line with <a href="#">links</a> and <span>spans</span>.</p> </div> ); }
Prettier实际格式化结果
const example = () => { return ( <div> <p> This is an example of a long line with <a href="#"> links </a> and <span> spans </span> . </p> </div> ); }
注:短行内容不会拆分,仅针对长行做换行处理。已尝试htmlWhitespaceSensitivity的三个选项,均未达到预期效果。
当前配置
Prettier配置
module.exports = { ...require('prettier-airbnb-config'), bracketSpacing: true, semi: true, singleQuote: true, jsxSingleQuote: true, objectWrap: 'preserve', bracketSameLine: true, htmlWhitespaceSensitivity: 'css', };
ESLint配置
import globals from "globals"; import pluginJs from "@eslint/js"; import tseslint from "typescript-eslint"; import pluginReact from "eslint-plugin-react"; /** @type {import('eslint').Linter.Config[]} */ export default [ {files: ["**/*.{js,mjs,cjs,ts,jsx,tsx}"]}, {languageOptions: { globals: globals.browser }}, pluginJs.configs.recommended, ...tseslint.configs.recommended, pluginReact.configs.flat.recommended, ];
已尝试方案
- 测试
htmlWhitespaceSensitivity的css、strict、ignore三个选项,无效果 - 尝试用ESLint规则覆盖Prettier的JSX格式化规则,无效
- 临时使用
// prettier-ignore禁用整个return块的格式化,扩展性差
解决方案
1. 使用prettier-plugin-inline-jsx插件
这个插件允许指定哪些JSX标签保持内联格式,仅在内容超过printWidth时才会换行。
安装插件
npm install prettier-plugin-inline-jsx --save-dev # 或 yarn add prettier-plugin-inline-jsx --dev
更新Prettier配置
在配置中添加插件和指定需要内联的标签:
module.exports = { ...require('prettier-airbnb-config'), bracketSpacing: true, semi: true, singleQuote: true, jsxSingleQuote: true, objectWrap: 'preserve', bracketSameLine: true, htmlWhitespaceSensitivity: 'css', plugins: ['prettier-plugin-inline-jsx'], // 指定需要保持内联的标签 inlineJsxTags: ['p', 'a', 'span'] };
2. 调整printWidth参数
将printWidth设置为更大的值(比如120或150),让短的内联内容不会被强制拆分,只有当内容真正超过行宽时才会换行。在Prettier配置中添加:
printWidth: 120
3. 局部精准禁用(适合少量场景)
如果不想安装插件,可以针对单个标签使用// prettier-ignore,但仅适合少量标签的场景:
const example = () => { return ( <div> {/* prettier-ignore */} <p>This is an example of a long line with <a href="#">links</a> and <span>spans</span>.</p> </div> ); }
内容的提问来源于stack exchange,提问作者Bill Hannah
相关产品推荐
相关产品推荐

