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

如何配置ESLint Stylistic实现相似行符号对齐及单行格式校验?

配置ESLint Stylistic实现多行符号/参数对齐并保留单行空格校验

1. 安装依赖

首先安装ESLint Stylistic的JS风格插件:

npm install @stylistic/eslint-plugin-js --save-dev
# 或使用yarn/pnpm
yarn add @stylistic/eslint-plugin-js --dev
pnpm add @stylistic/eslint-plugin-js -D

2. 配置ESLint规则

在你的ESLint配置文件(如.eslintrc.json、.eslintrc.js)中添加以下配置:

{
  "plugins": ["@stylistic/js"],
  "rules": {
    // 启用多行赋值、函数参数的对齐,忽略单行语句
    "@stylistic/js/align": ["error", {
      "assignments": true,
      "functionArguments": true,
      "ignoreSingleLine": true
    }],
    // 强制单行赋值等号前后仅保留一个空格
    "@stylistic/js/space-infix-ops": "error",
    // 禁止函数调用括号前出现多余空格
    "@stylistic/js/space-before-function-paren": ["error", {
      "anonymous": "never",
      "named": "never",
      "asyncArrow": "always"
    }],
    // 规范参数逗号前后空格:前无后有
    "@stylistic/js/comma-spacing": ["error", { "before": false, "after": true }]
  }
}

规则说明

  • @stylistic/js/align:核心规则,开启后会自动对齐多行赋值语句的等号,以及多行函数调用的参数;ignoreSingleLine: true确保单行语句不受对齐逻辑影响,交给其他空格规则校验。
  • space-infix-ops:修正单行中等号前后的多余空格,比如const manager = ...会被改成const manager = ...。
  • space-before-function-paren:移除函数调用括号后的多余空格,比如createUser( "John"会被改成createUser("John"。
  • comma-spacing:规范参数逗号前后的空格,比如"Doe", 25会被改成"Doe", 25。

效果示例

多行代码会被自动对齐为:

const manager = bank.createUser("John", "Doe",        25);
const admin   = bank.createUser("Max",  "Mustermann", 33);

单行错误代码:

const manager  = bank.createUser( "John", "Doe",   25);

会被修正为标准格式:

const manager = bank.createUser("John", "Doe", 25);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 02:47:07