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

如何配置ESLint indent规则适配TSX中HTML节点属性缩进?

如何让ESLint在TSX中使JSX属性换行后与标签起始位置对齐?

你当前的ESLint indent规则配置为:

"indent": [
  "error",
  4
]

期望实现的TSX格式是:换行后的JSX属性与标签的起始位置对齐,示例如下:

<BottomNavigation
       showLabels
       value={value}
       onChange={(…) => {
          …
       }}
    >
       <BottomNavigationAction component={Link} to="/contacts"…
                               icon={<ContactsIcon/>}/>
       <BottomNavigationAction … />
       <BottomNavigationAction
          component={Link} to="/groups" … icon={<GroupIcon/>}/>
    </BottomNavigation>

但默认的indent规则会强制换行后的属性缩进4个空格,不符合预期:

<BottomNavigation
       showLabels
       value={value}
       onChange={(…) => {
          …
       }}
    >
       <BottomNavigationAction component={Link} to="/contacts"…
          icon={<ContactsIcon/>}/>
       <BottomNavigationAction … />
       <BottomNavigationAction component={Link} to="/groups" …
          icon={<GroupIcon/>}/>
    </BottomNavigation>

原生ESLint的indent规则并不支持JSX属性的这种对齐方式,你需要借助eslint-plugin-react的专用规则来实现:

  1. 首先安装eslint-plugin-react(未安装的话):
npm install eslint-plugin-react --save-dev
  1. 在ESLint配置文件中启用插件,并配置react/jsx-indent-props规则为first:
{
  "plugins": ["react"],
  "rules": {
    "indent": [
      "error",
      4
    ],
    "react/jsx-indent-props": ["error", "first"]
  }
}

"first"选项会让换行后的JSX属性自动对齐到对应标签的起始位置,完全匹配你的需求。

如果是TSX文件,确保ESLint已配置@typescript-eslint/parser作为解析器,保证规则能正常作用于TSX语法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:18:30