如何配置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的专用规则来实现:
- 首先安装
eslint-plugin-react(未安装的话):
npm install eslint-plugin-react --save-dev
- 在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
相关产品推荐
相关产品推荐

