版本

no-multi-spaces

不允許過多的空格

🔧 可自動修正

此規則報告的某些問題可以透過 --fix 命令列 選項自動修正

重要

此規則已於 ESLint v8.53.0 棄用。請使用 @stylistic/eslint-plugin-js 中的對應規則

了解更多

連續多個空格若非用於縮排通常是錯誤。


if(foo  === "bar") {}

很難分辨,但在 foo=== 之間有兩個空格。像這樣的多個空格通常不被鼓勵,建議使用單個空格


if(foo === "bar") {}

規則詳情

此規則旨在禁止在邏輯運算式、條件運算式、宣告、陣列元素、物件屬性、序列和函數參數周圍使用多個空格。

此規則的錯誤程式碼範例

在測試區開啟
/*eslint no-multi-spaces: "error"*/

var a =  1;

if(foo   === "bar") {}

a <<  b

var arr = [1,  2];

a ?  b: c

此規則的正確程式碼範例

在測試區開啟
/*eslint no-multi-spaces: "error"*/

var a = 1;

if(foo === "bar") {}

a << b

var arr = [1, 2];

a ? b: c

選項

此規則的設定包含一個具有以下屬性的物件

  • "ignoreEOLComments": true(預設為 false)忽略行尾註解前的多個空格
  • "exceptions": { "Property": true }"Property" 是預設唯一指定的節點)指定要忽略的節點

ignoreEOLComments

使用 { "ignoreEOLComments": false }(預設)選項時,此規則的錯誤程式碼範例

在測試區開啟
/*eslint no-multi-spaces: ["error", { ignoreEOLComments: false }]*/

var x = 5;      // comment
var x = 5;      /* multiline
 * comment
 */

使用 { "ignoreEOLComments": false }(預設)選項時,此規則的正確程式碼範例

在測試區開啟
/*eslint no-multi-spaces: ["error", { ignoreEOLComments: false }]*/

var x = 5; // comment
var x = 5; /* multiline
 * comment
 */

使用 { "ignoreEOLComments": true } 選項時,此規則的正確程式碼範例

在測試區開啟
/*eslint no-multi-spaces: ["error", { ignoreEOLComments: true }]*/

var x = 5; // comment
var x = 5;      // comment
var x = 5; /* multiline
 * comment
 */
var x = 5;      /* multiline
 * comment
 */

exceptions

為了避免與其他需要多個空格的規則衝突,此規則具有 `exceptions` 選項來忽略某些節點。

此選項是一個物件,其屬性名稱應為 ESTree 定義的 AST 節點類型。確定 `exceptions` 的節點類型最簡單的方法是使用 AST Explorer 和 espree 解析器。

預設情況下僅忽略 `Property` 節點類型,因為對於 key-spacing 規則,某些對齊選項需要在物件實值中的屬性中使用多個空格。

預設 "exceptions": { "Property": true } 選項的正確程式碼範例

在測試區開啟
/*eslint no-multi-spaces: "error"*/
/*eslint key-spacing: ["error", { align: "value" }]*/

var obj = {
    first:  "first",
    second: "second"
};

"exceptions": { "Property": false } 選項的錯誤程式碼範例

在測試區開啟
/*eslint no-multi-spaces: ["error", { exceptions: { "Property": false } }]*/
/*eslint key-spacing: ["error", { align: "value" }]*/

var obj = {
    first:  "first",
    second: "second"
};

"exceptions": { "BinaryExpression": true } 選項的正確程式碼範例

在測試區開啟
/*eslint no-multi-spaces: ["error", { exceptions: { "BinaryExpression": true } }]*/

var a = 1  *  2;

"exceptions": { "VariableDeclarator": true } 選項的正確程式碼範例

在測試區開啟
/*eslint no-multi-spaces: ["error", { exceptions: { "VariableDeclarator": true } }]*/

var someVar      = 'foo';
var someOtherVar = 'barBaz';

"exceptions": { "ImportDeclaration": true } 選項的正確程式碼範例

在測試區開啟
/*eslint no-multi-spaces: ["error", { exceptions: { "ImportDeclaration": true } }]*/

import mod          from 'mod';
import someOtherMod from 'some-other-mod';

何時不該使用

如果您不想檢查和禁止多個空格,則應關閉此規則。

版本

此規則於 ESLint v0.9.0 版本中引入。

資源

變更語言