Error expected indentation of 6 spaces but found 4 indent

I am using VScode with latest version of Eslint. It is my first time using a linter. I keep getting this linting error when using a tab as indentation: severity: 'Error' message: 'Expected

I am using VScode with latest version of Eslint. It is my first time using a linter.

I keep getting this linting error when using a tab as indentation:

severity: ‘Error’
message: ‘Expected indentation of 1 tab but found 4 spaces. (indent)’
at: ‘4,5’
source: ‘eslint’

Here is my config file

{
"env": {
    "browser": true,
    "commonjs": true,
    "es6": true,
    "node": true
},
"extends": "eslint:recommended",
"rules": {
    "indent": [
        "error",
        "tab"
    ],
    "linebreak-style": [
        "error",
        "unix"
    ],
    "quotes": [
        "error",
        "single"
    ],
    "semi": [
        "error",
        "always"
    ]
}
}

I don’t understand why this error is being thrown as I indicated tabs for indentation. It is obviously calculating my 1 tab as 4 spaced but I don’t understand why it is doing that when I am pressing tab for indentation.

update: The reason is because in VScode using ctrl + shift + i to beautify code will actually use spaces and not tabs. That is the reason.

Сергей Грузнов

Всем привет!
Прошел упражнение и все засчиталось, но не понимаю, почему вылезают эти ошибки:

/usr/src/app/finalGrade.js
3:1 error Expected indentation of 2 spaces but found 0 indent
4:1 error Expected indentation of 4 spaces but found 2 indent
5:1 error Expected indentation of 2 spaces but found 0 indent
5:1 error Closing curly brace does not appear on the same line as the subsequent block brace-style
6:1 error Expected indentation of 2 spaces but found 0 indent
6:7 error Multiple spaces found before ‘if’ no-multi-spaces
6:7 error Unnecessary ‘else’ after ‘return’ no-else-return
6:16 error Operator ‘>’ must be spaced space-infix-ops
6:32 error Operator ‘>=’ must be spaced space-infix-ops
7:1 error Expected indentation of 4 spaces but found 2 indent
8:1 error Expected indentation of 2 spaces but found 0 indent
8:1 error Closing curly brace does not appear on the same line as the subsequent block brace-style
9:1 error Expected indentation of 2 spaces but found 0 indent
9:14 error Operator ‘>’ must be spaced space-infix-ops
9:29 error Operator ‘>=’ must be spaced space-infix-ops
10:1 error Expected indentation of 4 spaces but found 2 indent
11:1 error Closing curly brace does not appear on the same line as the subsequent block brace-style
11:1 error Expected indentation of 2 spaces but found 0 indent
12:1 error Expected indentation of 2 spaces but found 0 indent
13:1 error Expected indentation of 4 spaces but found 2 indent
14:1 error Expected indentation of 2 spaces but found 0 indent
15:2 error Missing semicolon semi
16:1 error More than 2 blank lines not allowed no-multiple-empty-lines

Подскажите пожалуйста)


4


0

Иван Яковенко

Привет! Это ошибки Линтера в оформлении кода.


0

Сергей К.

Линтер проверяет качество кода, стиль написания. Но мы настоятельно рекомендуем исправлять все его замечания.


0

Сергей Грузнов

Я понимаю, что где то ошибка, просто не понимаю где именно и как ее исправить?)


0

Сергей Грузнов

а, все понял) суть в оформлении кода)
Всем спасибо!)


0

Как использовать ESLint, чтобы повысить качество кода JavaScript и TypeScript


JavaScript по умолчанию имеет очень гибкий синтаксис. Он позволяет менять тип переменной, использовать одинарные и двойные кавычки для строк и любое количество пробелов для отступов, опускать точки с запятой в конце и т.д.

Skillfactory.ru

Однако каждая команда должна придерживаться единого стандарта программирования. Так код будет легче просматривать и поддерживать. В этом помогает ESLint.

ESLint  —  инструмент статической проверки кода, используемый для мониторинга качества и стилистической выдержанности кода JavaScript. TSLint, применявшийся ранее для проверки кода на TypeScript, уже устарел. Сегодня ESLint используется и для кода TypeScript.

Начинать работу с ESLint может быть непросто, особенно если проверять с его помощью код TypeScript. Предлагаем практическое руководство, которое поможет установить и настроить ESLint для проектов на JavaScript и TypeScript.


Установите Node.js

Пакет ESLint будет установлен менеджером пакетов Node (npm). Поэтому потребуется установить на компьютер Node.js. Его можно загрузить по этой ссылке. Команды для установки Node.js в системе Linux приведены ниже. Обратите внимание, что в версию системы со временем будут вноситься изменения, но команды останутся прежними.

# Загрузите пакет с сайта https://nodejs.org/en/

# Разархивируйте файлы в место назначения, например в базовый каталог.
$ cd $HOME/Downloads
$ tar xvf node-v18.7.0-linux-x64.tar.xz -C $HOME

# Добавьте путь к папке `/bin` в `PATH` в `.bashrc`, чтобы 
# система могла найти исполняемые файлы:
$ export PATH=$PATH:$HOME/node-v18.7.0-linux-x64/bin

Настройте папку проекта

Если вы работаете с JS-фреймворком, то папка проекта обычно создается автоматически. Тем не менее создадим ее с нуля, чтобы настройки, введенные позже, можно было использовать повсеместно. Для инициирования проекта Node.js выполните следующие команды:

# Создайте папку проекта и перейдите в нее:
$ mkdir js-ts-linting-example
$ cd js-ts-linting-example

# Инициируйте проект, а именно сгенерируйте начальный `package.json`:
$ npm init

Введите информацию о проекте, следуя указаниям мастера настройки. На основе предоставленной информации будет создан файл package.json. Поскольку проект может быть создан не на Node.js, шаблонный код, такой как main: index.js, можно удалить. Мы обновим раздел scripts позже, когда ESLint будет установлен и настроен.


Установка ESLint и настройка конфигурационного файла

Чтобы установить и настроить ESLint, выполните следующую команду:

$ npm init @eslint/config

Выберите опции, которые лучше всего подходят для проекта, и файл package.json будет обновлен соответствующим образом. Для данного проекта были выбраны следующие опции:

✔ How would you like to use ESLint? · style
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · none
✔ Does your project use TypeScript? · Yes
✔ Where does your code run? · browser
✔ How would you like to define a style for your project? · guide
✔ Which style guide do you want to follow? · standard
✔ What format do you want your config file to be in? · JavaScript

Если в проекте не используется TypeScript, можно пропустить опции для TypeScript в процессе установки. В противном случае нужно будет установить и TypeScript:

$ npm install --save-dev typescript

На этом этапе файл package.json будет выглядеть следующим образом:

{
"name": "js-ts-linting-example",
"version": "1.0.0",
"description": "Demo project for setting up ESLint for JavaScript/TypeScript code.",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "Lynn",
"license": "ISC",
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.33.0",
"@typescript-eslint/parser": "^5.33.0",
"eslint": "^8.21.0",
"eslint-config-standard": "^17.0.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-n": "^15.2.4",
"eslint-plugin-promise": "^6.0.0",
"typescript": "^4.7.4"
}
}

Чтобы использовать ESLint для кода TypeScript, потребуется файл конфигурации для TypeScript под названием tsconfig.json. Этот файл обычно автоматически генерируется JS-фреймворками, такими как Angular. Если же его нужно создать с нуля, выполните эту команду с помощью npx:

$ npx tsc --init

Будет создан файл tsconfig.json со множеством шаблонов кода, большинство из которых не нужно менять. Вы можете настроить их соответствующим образом, исходя из ваших требований.

Теперь последнее и самое главное. Возможно, вы заметили, что автоматически был создан файл конфигурации под названием .eslintrc.js. Если этого не произошло, вам нужно создать его вручную и скопировать в него приведенные ниже настройки.

Этот файл содержит пользовательские настройки для ESLint. Для проекта, написанного на JavaScript, можно использовать его напрямую, если вам не нужны пользовательские настройки. Однако нам нужно добавить настройки, прежде чем использовать его для проверки кода TypeScript. Кроме того, мы добавим несколько правил для проверки кода. Обновленный файл .eslintrc.js имеет следующее содержание:

module.exports = {
env: {
browser: true,
es2021: true
},
extends: [
'standard',
'eslint:recommended',
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
},
plugins: [
'@typescript-eslint' // Для TypeScript.
],
overrides: [ // Используем `overrides`, чтобы ESLint мог проверять файлы как JS, так и TS.
{
files: ['*.ts', '*.tsx'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking',
],
parserOptions: {
tsconfigRootDir: __dirname,
project: ['./tsconfig.json'],
},
},
],
ignorePatterns: ['.eslintrc.js'],
rules: {
quotes: ["error", "double"], // Использовать двойные кавычки.
semi: ["error", "always"], // Всегда добавлять точку с запятой в конце утверждения.
indent: ["error", 2], // Отступ — это два пробела.
"no-console": "error" // Избегать использования в коде методов на консоли (`console`).
}
}

Важно отметить, что потребуется добавить настройки для кода TypeScript в разделе overrides, иначе ESLint не получится использовать для одновременной проверки кода JavaScript и TypeScript.

Для правил ключами являются имена правил, которые можно найти здесь, а значениями  —  действия для соответствующих правил. Если значение является строкой или числом, то это уровень ошибок. В данном случае error или 2 означает, что нарушение правила вернет ошибку, и код выхода будет равен 1. Если значение представляет собой массив, то первый элемент  —  это уровень ошибок, а второй  —  конфигурация для правила. Например, первое правило определяет, что следует использовать только двойные кавычки, иначе будет возвращена ошибка.

Если увидите в IDE предупреждение о том, что .eslintrc.js не включен ни в один путь компилятором TypeScript, то либо добавьте его в линтинг, либо проигнорируйте его. Игнорировать проще: нужно просто добавить новый ключ ignorePatterns, как показано выше, или добавить его в файл .eslintignore. Если хотите также линтить этот файл, добавьте его в tsconfig.config. Если нужно добавить .eslintrc.js для линтинга, обратитесь к этому обсуждению на StackOverflow.

Если увидите сообщение TS2304:Cannot find name '__dirname' в .eslintrc.js, выполните эту команду, чтобы исправить возникшую ошибку:

$ npm install @types/node --save-dev

Использование ESLint для проверки кода JavaScript

Теперь, когда ESLint установлен и настроен, добавим этот JS-файл в папку проекта и применим ESLint для его проверки. Все используемые здесь файлы можно найти в конце статьи.

function sum(x, y) {
    return x + y
}

const x = 100;
const y = '200';
const xPlusY = sum(x, y);
console.log(`${x} + ${y} = ${xPlusY}`)

В этом файле есть несколько очевидных ошибок и нестандартное форматирование, которые могут быть проверены и исправлены с помощью ESLint.

Если хотите, чтобы ESLint проверил только код, выполните эту команду:

$ npx eslint src/example.js

Вы увидите ошибки, которые стоит исправить для улучшения кода:

1:13  error  Missing space before function parentheses     space-before-function-paren
  2:1   error  Expected indentation of 2 spaces but found 4  indent
  2:17  error  Missing semicolon                             semi
  6:11  error  Strings must use doublequote                  quotes
  8:1   error  Unexpected console statement                  no-console
  8:39  error  Missing semicolon                             semi

✖ 6 problems (6 errors, 0 warnings)
  5 errors and 0 warnings potentially fixable with the `--fix` option.

Если хотите, чтобы ESLint автоматически исправлял код, добавьте опцию --fix к вышеуказанной команде:

$ npx eslint src/example.js --fix

Большинство косметических погрешностей могут быть исправлены ESLint автоматически. Однако есть некоторые проблемы, которые необходимо исправлять вручную. Например, ESLint не удалит console.log автоматически  —  вам придется удалять его самостоятельно:

8:1  error  Unexpected console statement  no-console

✖ 1 problem (1 error, 0 warnings)

Использование ESLint для проверки кода TypeScript

Теперь воспользуемся ESLint для проверки этого файла, написанного на TypeScript. Он имеет то же содержание, что и файл на JavaScript, за исключением того, что в функции добавлены типы:

function sum(x: number, y: number): number {
    return x + y
}

const x = 100;
const y = '200';
const xPlusY = sum(x, y);
console.log(`${x} + ${y} = ${xPlusY}`)

Для проверки кода TypeScript используется та же команда. Можно специально указать расширение, но это необязательно:

$ npx eslint --ext .ts src/example.ts

Будут выданы такие же ошибки:

1:13  error  Missing space before function parentheses     space-before-function-paren
  2:1   error  Expected indentation of 2 spaces but found 4  indent
  2:17  error  Missing semicolon                             semi
  8:1   error  Unexpected console statement                  no-console
  8:39  error  Missing semicolon                             semi

✖ 5 problems (5 errors, 0 warnings)
  4 errors and 0 warnings potentially fixable with the `--fix` option.

Однако в коде TypeScript кавычки не проверяются  —  это известная проблема. Чтобы проверять кавычки в коде TypeScript, вам придется обновить правила в соответствии с этой инструкцией:

{
// Другие правила в исходном файле.
"quotes": "off", // Обратите внимание: вы должны отключить базовое правило, так как оно может сообщать о неправильных ошибках.
"@typescript-eslint/quotes": ["error", "dobule"]
}

Кроме того, проблему с кавычками для кода TypeScript можно легко исправить с помощью Prettier.


Использование tsc для проверки кода TypeScript

Следует отметить, что непоследовательный тип в строке 7 в example.ts не указывается ESLint. К сожалению, ESLint сообщает только об ошибках собственных линтеров, игнорируя ошибки компиляции TypeScript.

Проверить ошибки компиляции TypeScript для типов, как показано в нашем примере, можно с помощью команды tsc. Обычно к ней добавляется опция --noEmit, поскольку чаще всего нужно проверить только ошибки компиляции (без создания скомпилированных файлов JavaScript).

Воспользуемся tsc для проверки кода TypeScript:

$ npx tsc src/example.ts --noEmit

Теперь видим непоследовательный тип в строке 7 при вызове функции sum:

example.ts:7:23 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

7 const xPlusY = sum(x, y);
                        ~
Found 1 error in example.ts:7

Добавление скриптов для линтинга в package.json

Добавим несколько скриптов в package.json, которые можно будет легко вызывать для проверки всех файлов в проекте:

"scripts": {
"check-types": "npx tsc --noEmit",
"lint": "npx eslint 'src/**/*.{js,jsx,ts,tsx}'"
}

Обратите внимание, что можно добавлять расширения файлов в eslint, но не в tsc.

Теперь запустим проверку типов и линтинг для всех файлов в проекте:

Skillfactory.ru

$ npm run check-types
$ npm run lint

Использование ESLint в VS Code

Использование ESLint в командной строке является обязательным, если необходимо добавить его в конвейеры проверки кода, такие как Git-хуки pre-commit. При написании кода желательно иметь обратную связь с интерактивной средой разработки (IDE) в режиме реального времени, чтобы была возможность немедленно исправлять проблемы. Использование VS Code позволяет установить расширение ESLint для проверки кода именно в таком режиме.

Обратите внимание, что расширение ESLint использует один и тот же конфигурационный файл в папке проекта. Включите строку состояния ESLint, чтобы видеть ошибки, если файл .eslintrc.js настроен неправильно:

Теперь при внесении какой-либо ошибки в .eslintrc.js вы сможете сразу же увидеть ее с помощью сообщения об ошибке:

Наконец, если расширение ESLint установлено и включено, а файл .eslintrc.js настроен правильно, можно сразу же увидеть ошибки в VS Code:


Теперь вы знаете, как установить и настроить ESLint для проверки качества и стилистической выдержанности кода JavaScript и TypeScript. Весь код из статьи можно найти в этом репозитории.

Читайте также:

  • 7 способов ускорить ревью кода
  • Как не лажать с JavaScript. Часть 3
  • Создаем на JavaScript приложение записи заметок в реальном времени

Читайте нас в Telegram, VK и Дзен


Перевод статьи Lynn Kwong: How Use ESLint to Write Elegant Code in JavaScript and TypeScript

How to set "indent" in .eslintr.json to match the default used in WebStorm?

enter image description here

Everything I’ve tried so far, as per the official documentation can’t match it:

  • "indent": ["error", 2] – gives many Expected indentation of 2 spaces but found 4
  • "indent": ["error", 4] – gives many Expected indentation of 4 spaces but found 8
  • "indent": ["error", 8] – gives many Expected indentation of 8 spaces but found 4

My complete eslint configuration:

{
  "env": {
    "es6": true,
    "node": true,
    "jasmine": true
  },
  "extends": "eslint:recommended",
  "parserOptions": {
  },
  "rules": {
    "no-else-return": "error",
    "no-multi-spaces": "error",
    "no-whitespace-before-property": "error",
    "camelcase": "error",
    "new-cap": "error",
    "no-console": "error",
    "comma-dangle": "error",
    "no-var": "error",
    "indent": ["error", 4],
    "quotes": [
      "error",
      "single"
    ],
    "semi": [
      "error",
      "always"
    ]
  }
}

As I type the code, I always use Ctrl+Alt+L to auto-format the code, and the code formatting produced doesn’t comply with any eslint settings.


UPDATE

As was asked, a code example for "indent": ["error", 4]:

For this code: (formatted via Ctrl+Alt+L)

const a = 123;
switch (a) {
    case 1:
        return 1;
    case 2:
        return 2;
    case 3:
        return 3;
    default:
        break;
}

results in:

3:1  error  Expected indentation of 0 spaces but found 4
4:1  error  Expected indentation of 4 spaces but found 8
5:1  error  Expected indentation of 0 spaces but found 4
6:1  error  Expected indentation of 4 spaces but found 8
7:1  error  Expected indentation of 0 spaces but found 4
8:1  error  Expected indentation of 4 spaces but found 8
9:1  error  Expected indentation of 0 spaces but found 4
10:1  error  Expected indentation of 4 spaces but found 8

example 2

obj.format('text', {
        value: '${two}'
    }
);

results in:

2:1   error  Expected indentation of 4 spaces but found 8
3:1   error  Expected indentation of 0 spaces but found 4

example 3

return begin()
    .then(() => {
            return callback()
                .then(data => {
                    success = true;
                    return commit();
                }, reason => {
                    return rollback();
                })
        },
        function (reason) {
            update(false, false, reason);
            return $p.reject(reason);
        });

results in:

3:1   error  Expected indentation of 8 spaces but found 12
4:1   error  Expected indentation of 12 spaces but found 16
5:1   error  Expected indentation of 16 spaces but found 20
6:1   error  Expected indentation of 16 spaces but found 20
7:1   error  Expected indentation of 12 spaces but found 16
8:1   error  Expected indentation of 16 spaces but found 20
9:1   error  Expected indentation of 12 spaces but found 16
10:1   error  Expected indentation of 4 spaces but found 8
11:1   error  Expected indentation of 4 spaces but found 8
12:1   error  Expected indentation of 8 spaces but found 12
13:1   error  Expected indentation of 8 spaces but found 12
14:1   error  Expected indentation of 4 spaces but found 8

Advertisement

Answer

Switch-Case seems to be a special case for eslint regarding indentation. Per default the case clauses are not indented relative to the switch:

“SwitchCase” (default: 0) enforces indentation level for case clauses
in switch statements

See here for an example: http://eslint.org/docs/rules/indent#switchcase

You need to set SwitchCase option to 1 like so:

"indent": [
    "error", 
    4, 
    {"SwitchCase": 1}
]

So your complete eslint config will now look like this:

{
    "env": {
        "es6": true,
        "node": true,
        "jasmine": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
    },
    "rules": {
        "no-else-return": "error",
        "no-multi-spaces": "error",
        "no-whitespace-before-property": "error",
        "camelcase": "error",
        "new-cap": "error",
        "no-console": "error",
        "comma-dangle": "error",
        "no-var": "error",
        "indent": ["error", 4, {"SwitchCase": 1}],
        "quotes": [
            "error",
            "single"
        ],
        "semi": [
            "error",
            "always"
        ]
    }
}

Regarding your 2nd example I think it is common to write it like this:

obj.format('text', {
    value: '${two}'
});

Both parenthesis are opened on the same line, so you close them on the same line. If you use auto format on that lines, they will not change.

The third example looks a bit tricky. I don’t know if you can get eslint and auto format on the same page for that one. I personally would prefer the eslint way, but I don’t know if you can tweak the auto format to do it like that.

Edit: You could write it like that:

return begin()
    .then(() => callback()
        .then(data => {
            success = true;
            return commit();
        }, reason => {
            return rollback();
        }),
        function(reason) {
            update(false, false, reason);
            return $p.reject(reason);
        });

1 People found this is helpful

Switch-case, по-видимому, является особым случаем для eslint относительно отступа. По умолчанию предложения case не имеют отступ по отношению к switch:

«SwitchCase» (по умолчанию: 0) применяет уровень отступов для предложений case в операторах switch

См. здесь пример: http://eslint.org/docs/rules/indent#switchcase

Вам нужно установить для параметра SwitchCase значение 1 следующим образом:

"indent": [
    "error", 
    4, 
    {"SwitchCase": 1}
]

Итак, ваша полная конфигурация eslint будет выглядеть следующим образом:

{
    "env": {
        "es6": true,
        "node": true,
        "jasmine": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
    },
    "rules": {
        "no-else-return": "error",
        "no-multi-spaces": "error",
        "no-whitespace-before-property": "error",
        "camelcase": "error",
        "new-cap": "error",
        "no-console": "error",
        "comma-dangle": "error",
        "no-var": "error",
        "indent": ["error", 4, {"SwitchCase": 1}],
        "quotes": [
            "error",
            "single"
        ],
        "semi": [
            "error",
            "always"
        ]
    }
}

Что касается вашего второго примера, я думаю, что его обычно пишут следующим образом:

obj.format('text', {
    value: '${two}'
});

Обе скобки открываются в одной строке, поэтому вы закрываете их в одной строке. Если вы используете автоматический формат в этих строках, они не будут меняться.

Третий пример выглядит несколько сложнее. Я не знаю, можете ли вы получить eslint и автоматический формат на одной странице для этого. Я лично предпочел бы eslint, но я не знаю, можете ли вы настроить автоматический формат, чтобы сделать это так.

Изменить: вы можете написать так:

return begin()
    .then(() => callback()
        .then(data => {
            success = true;
            return commit();
        }, reason => {
            return rollback();
        }),
        function(reason) {
            update(false, false, reason);
            return $p.reject(reason);
        });

Enforce consistent indentation

🔧 Fixable

Some problems reported by this rule are automatically fixable by the --fix command line option

There are several common guidelines which require specific indentation of nested blocks and statements, like:

function hello(indentSize, type) {
    if (indentSize === 4 && type !== 'tab') {
        console.log('Each next indentation will increase on 4 spaces');
    }
}

These are the most common scenarios recommended in different style guides:

  • Two spaces, not longer and no tabs: Google, npm, Node.js, Idiomatic, Felix
  • Tabs: jQuery
  • Four spaces: Crockford

Rule Details

This rule enforces a consistent indentation style. The default style is 4 spaces.

Options

This rule has a mixed option:

For example, for 2-space indentation:

{
    "indent": ["error", 2]
}

Or for tabbed indentation:

{
    "indent": ["error", "tab"]
}

Examples of incorrect code for this rule with the default options:

/*eslint indent: "error"*/

if (a) {
  b=c;
  function foo(d) {
    e=f;
  }
}

Examples of correct code for this rule with the default options:

/*eslint indent: "error"*/

if (a) {
    b=c;
    function foo(d) {
        e=f;
    }
}

This rule has an object option:

  • "ignoredNodes" can be used to disable indentation checking for any AST node. This accepts an array of selectors. If an AST node is matched by any of the selectors, the indentation of tokens which are direct children of that node will be ignored. This can be used as an escape hatch to relax the rule if you disagree with the indentation that it enforces for a particular syntactic pattern.
  • "SwitchCase" (default: 0) enforces indentation level for case clauses in switch statements
  • "VariableDeclarator" (default: 1) enforces indentation level for var declarators; can also take an object to define separate rules for var, let and const declarations. It can also be "first", indicating all the declarators should be aligned with the first declarator.
  • "outerIIFEBody" (default: 1) enforces indentation level for file-level IIFEs. This can also be set to "off" to disable checking for file-level IIFEs.
  • "MemberExpression" (default: 1) enforces indentation level for multi-line property chains. This can also be set to "off" to disable checking for MemberExpression indentation.
  • "FunctionDeclaration" takes an object to define rules for function declarations.
    • parameters (default: 1) enforces indentation level for parameters in a function declaration. This can either be a number indicating indentation level, or the string "first" indicating that all parameters of the declaration must be aligned with the first parameter. This can also be set to "off" to disable checking for FunctionDeclaration parameters.
    • body (default: 1) enforces indentation level for the body of a function declaration.
  • "FunctionExpression" takes an object to define rules for function expressions.
    • parameters (default: 1) enforces indentation level for parameters in a function expression. This can either be a number indicating indentation level, or the string "first" indicating that all parameters of the expression must be aligned with the first parameter. This can also be set to "off" to disable checking for FunctionExpression parameters.
    • body (default: 1) enforces indentation level for the body of a function expression.
  • "StaticBlock" takes an object to define rules for class static blocks.
    • body (default: 1) enforces indentation level for the body of a class static block.
  • "CallExpression" takes an object to define rules for function call expressions.
    • arguments (default: 1) enforces indentation level for arguments in a call expression. This can either be a number indicating indentation level, or the string "first" indicating that all arguments of the expression must be aligned with the first argument. This can also be set to "off" to disable checking for CallExpression arguments.
  • "ArrayExpression" (default: 1) enforces indentation level for elements in arrays. It can also be set to the string "first", indicating that all the elements in the array should be aligned with the first element. This can also be set to "off" to disable checking for array elements.
  • "ObjectExpression" (default: 1) enforces indentation level for properties in objects. It can be set to the string "first", indicating that all properties in the object should be aligned with the first property. This can also be set to "off" to disable checking for object properties.
  • "ImportDeclaration" (default: 1) enforces indentation level for import statements. It can be set to the string "first", indicating that all imported members from a module should be aligned with the first member in the list. This can also be set to "off" to disable checking for imported module members.
  • "flatTernaryExpressions": true (false by default) requires no indentation for ternary expressions which are nested in other ternary expressions.
  • "offsetTernaryExpressions": true (false by default) requires indentation for values of ternary expressions.
  • "ignoreComments" (default: false) can be used when comments do not need to be aligned with nodes on the previous or next line.

Level of indentation denotes the multiple of the indent specified. Example:

  • Indent of 4 spaces with VariableDeclarator set to 2 will indent the multi-line variable declarations with 8 spaces.
  • Indent of 2 spaces with VariableDeclarator set to 2 will indent the multi-line variable declarations with 4 spaces.
  • Indent of 2 spaces with VariableDeclarator set to {"var": 2, "let": 2, "const": 3} will indent the multi-line variable declarations with 4 spaces for var and let, 6 spaces for const statements.
  • Indent of tab with VariableDeclarator set to 2 will indent the multi-line variable declarations with 2 tabs.
  • Indent of 2 spaces with SwitchCase set to 0 will not indent case clauses with respect to switch statements.
  • Indent of 2 spaces with SwitchCase set to 1 will indent case clauses with 2 spaces with respect to switch statements.
  • Indent of 2 spaces with SwitchCase set to 2 will indent case clauses with 4 spaces with respect to switch statements.
  • Indent of tab with SwitchCase set to 2 will indent case clauses with 2 tabs with respect to switch statements.
  • Indent of 2 spaces with MemberExpression set to 0 will indent the multi-line property chains with 0 spaces.
  • Indent of 2 spaces with MemberExpression set to 1 will indent the multi-line property chains with 2 spaces.
  • Indent of 2 spaces with MemberExpression set to 2 will indent the multi-line property chains with 4 spaces.
  • Indent of 4 spaces with MemberExpression set to 0 will indent the multi-line property chains with 0 spaces.
  • Indent of 4 spaces with MemberExpression set to 1 will indent the multi-line property chains with 4 spaces.
  • Indent of 4 spaces with MemberExpression set to 2 will indent the multi-line property chains with 8 spaces.

tab

Examples of incorrect code for this rule with the "tab" option:

/*eslint indent: ["error", "tab"]*/

if (a) {
     b=c;
function foo(d) {
           e=f;
 }
}

Examples of correct code for this rule with the "tab" option:

/*eslint indent: ["error", "tab"]*/

if (a) {
/*tab*/b=c;
/*tab*/function foo(d) {
/*tab*//*tab*/e=f;
/*tab*/}
}

ignoredNodes

The following configuration ignores the indentation of ConditionalExpression (“ternary expression”) nodes:

Examples of correct code for this rule with the 4, { "ignoredNodes": ["ConditionalExpression"] } option:

/*eslint indent: ["error", 4, { "ignoredNodes": ["ConditionalExpression"] }]*/

var a = foo
      ? bar
      : baz;

var a = foo
                ? bar
: baz;

The following configuration ignores indentation in the body of IIFEs.

Examples of correct code for this rule with the 4, { "ignoredNodes": ["CallExpression > FunctionExpression.callee > BlockStatement.body"] } option:

/*eslint indent: ["error", 4, { "ignoredNodes": ["CallExpression > FunctionExpression.callee > BlockStatement.body"] }]*/

(function() {

foo();
bar();

})

All AST node types can be found at ESTree specification. You can use AST Explorer with the espree parser to examine AST tree of a code snippet.

SwitchCase

Examples of incorrect code for this rule with the 2, { "SwitchCase": 1 } options:

/*eslint indent: ["error", 2, { "SwitchCase": 1 }]*/

switch(a){
case "a":
    break;
case "b":
    break;
}

Examples of correct code for this rule with the 2, { "SwitchCase": 1 } option:

/*eslint indent: ["error", 2, { "SwitchCase": 1 }]*/

switch(a){
  case "a":
    break;
  case "b":
    break;
}

VariableDeclarator

Examples of incorrect code for this rule with the 2, { "VariableDeclarator": 1 } options:

/*eslint indent: ["error", 2, { "VariableDeclarator": 1 }]*/
/*eslint-env es6*/

var a,
    b,
    c;
let a,
    b,
    c;
const a = 1,
    b = 2,
    c = 3;

Examples of correct code for this rule with the 2, { "VariableDeclarator": 1 } options:

/*eslint indent: ["error", 2, { "VariableDeclarator": 1 }]*/
/*eslint-env es6*/

var a,
  b,
  c;
let a,
  b,
  c;
const a = 1,
  b = 2,
  c = 3;

Examples of correct code for this rule with the 2, { "VariableDeclarator": 2 } options:

/*eslint indent: ["error", 2, { "VariableDeclarator": 2 }]*/
/*eslint-env es6*/

var a,
    b,
    c;
let a,
    b,
    c;
const a = 1,
    b = 2,
    c = 3;

Examples of incorrect code for this rule with the 2, { "VariableDeclarator": "first" } options:

/*eslint indent: ["error", 2, { "VariableDeclarator": "first" }]*/
/*eslint-env es6*/

var a,
  b,
  c;
let a,
  b,
  c;
const a = 1,
  b = 2,
  c = 3;

Examples of correct code for this rule with the 2, { "VariableDeclarator": "first" } options:

/*eslint indent: ["error", 2, { "VariableDeclarator": "first" }]*/
/*eslint-env es6*/

var a,
    b,
    c;
let a,
    b,
    c;
const a = 1,
      b = 2,
      c = 3;

Examples of correct code for this rule with the 2, { "VariableDeclarator": { "var": 2, "let": 2, "const": 3 } } options:

/*eslint indent: ["error", 2, { "VariableDeclarator": { "var": 2, "let": 2, "const": 3 } }]*/
/*eslint-env es6*/

var a,
    b,
    c;
let a,
    b,
    c;
const a = 1,
      b = 2,
      c = 3;

outerIIFEBody

Examples of incorrect code for this rule with the options 2, { "outerIIFEBody": 0 }:

/*eslint indent: ["error", 2, { "outerIIFEBody": 0 }]*/

(function() {

  function foo(x) {
    return x + 1;
  }

})();

if (y) {
console.log('foo');
}

Examples of correct code for this rule with the options 2, { "outerIIFEBody": 0 }:

/*eslint indent: ["error", 2, { "outerIIFEBody": 0 }]*/

(function() {

function foo(x) {
  return x + 1;
}

})();

if (y) {
   console.log('foo');
}

Examples of correct code for this rule with the options 2, { "outerIIFEBody": "off" }:

/*eslint indent: ["error", 2, { "outerIIFEBody": "off" }]*/

(function() {

function foo(x) {
  return x + 1;
}

})();

(function() {

  function foo(x) {
    return x + 1;
  }

})();

if (y) {
  console.log('foo');
}

MemberExpression

Examples of incorrect code for this rule with the 2, { "MemberExpression": 1 } options:

/*eslint indent: ["error", 2, { "MemberExpression": 1 }]*/

foo
.bar
.baz()

Examples of correct code for this rule with the 2, { "MemberExpression": 1 } option:

/*eslint indent: ["error", 2, { "MemberExpression": 1 }]*/

foo
  .bar
  .baz();

FunctionDeclaration

Examples of incorrect code for this rule with the 2, { "FunctionDeclaration": {"body": 1, "parameters": 2} } option:

/*eslint indent: ["error", 2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }]*/

function foo(bar,
  baz,
  qux) {
    qux();
}

Examples of correct code for this rule with the 2, { "FunctionDeclaration": {"body": 1, "parameters": 2} } option:

/*eslint indent: ["error", 2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }]*/

function foo(bar,
    baz,
    qux) {
  qux();
}

Examples of incorrect code for this rule with the 2, { "FunctionDeclaration": {"parameters": "first"} } option:

/*eslint indent: ["error", 2, {"FunctionDeclaration": {"parameters": "first"}}]*/

function foo(bar, baz,
  qux, boop) {
  qux();
}

Examples of correct code for this rule with the 2, { "FunctionDeclaration": {"parameters": "first"} } option:

/*eslint indent: ["error", 2, {"FunctionDeclaration": {"parameters": "first"}}]*/

function foo(bar, baz,
             qux, boop) {
  qux();
}

FunctionExpression

Examples of incorrect code for this rule with the 2, { "FunctionExpression": {"body": 1, "parameters": 2} } option:

/*eslint indent: ["error", 2, { "FunctionExpression": {"body": 1, "parameters": 2} }]*/

var foo = function(bar,
  baz,
  qux) {
    qux();
}

Examples of correct code for this rule with the 2, { "FunctionExpression": {"body": 1, "parameters": 2} } option:

/*eslint indent: ["error", 2, { "FunctionExpression": {"body": 1, "parameters": 2} }]*/

var foo = function(bar,
    baz,
    qux) {
  qux();
}

Examples of incorrect code for this rule with the 2, { "FunctionExpression": {"parameters": "first"} } option:

/*eslint indent: ["error", 2, {"FunctionExpression": {"parameters": "first"}}]*/

var foo = function(bar, baz,
  qux, boop) {
  qux();
}

Examples of correct code for this rule with the 2, { "FunctionExpression": {"parameters": "first"} } option:

/*eslint indent: ["error", 2, {"FunctionExpression": {"parameters": "first"}}]*/

var foo = function(bar, baz,
                   qux, boop) {
  qux();
}

StaticBlock

Examples of incorrect code for this rule with the 2, { "StaticBlock": {"body": 1} } option:

/*eslint indent: ["error", 2, { "StaticBlock": {"body": 1} }]*/

class C {
  static {
      foo();
  }
}

Examples of correct code for this rule with the 2, { "StaticBlock": {"body": 1} } option:

/*eslint indent: ["error", 2, { "StaticBlock": {"body": 1} }]*/

class C {
  static {
    foo();
  }
}

Examples of incorrect code for this rule with the 2, { "StaticBlock": {"body": 2} } option:

/*eslint indent: ["error", 2, { "StaticBlock": {"body": 2} }]*/

class C {
  static {
    foo();
  }
}

Examples of correct code for this rule with the 2, { "StaticBlock": {"body": 2} } option:

/*eslint indent: ["error", 2, { "StaticBlock": {"body": 2} }]*/

class C {
  static {
      foo();
  }
}

CallExpression

Examples of incorrect code for this rule with the 2, { "CallExpression": {"arguments": 1} } option:

/*eslint indent: ["error", 2, { "CallExpression": {"arguments": 1} }]*/

foo(bar,
    baz,
      qux
);

Examples of correct code for this rule with the 2, { "CallExpression": {"arguments": 1} } option:

/*eslint indent: ["error", 2, { "CallExpression": {"arguments": 1} }]*/

foo(bar,
  baz,
  qux
);

Examples of incorrect code for this rule with the 2, { "CallExpression": {"arguments": "first"} } option:

/*eslint indent: ["error", 2, {"CallExpression": {"arguments": "first"}}]*/

foo(bar, baz,
  baz, boop, beep);

Examples of correct code for this rule with the 2, { "CallExpression": {"arguments": "first"} } option:

/*eslint indent: ["error", 2, {"CallExpression": {"arguments": "first"}}]*/

foo(bar, baz,
    baz, boop, beep);

ArrayExpression

Examples of incorrect code for this rule with the 2, { "ArrayExpression": 1 } option:

/*eslint indent: ["error", 2, { "ArrayExpression": 1 }]*/

var foo = [
    bar,
baz,
      qux
];

Examples of correct code for this rule with the 2, { "ArrayExpression": 1 } option:

/*eslint indent: ["error", 2, { "ArrayExpression": 1 }]*/

var foo = [
  bar,
  baz,
  qux
];

Examples of incorrect code for this rule with the 2, { "ArrayExpression": "first" } option:

/*eslint indent: ["error", 2, {"ArrayExpression": "first"}]*/

var foo = [bar,
  baz,
  qux
];

Examples of correct code for this rule with the 2, { "ArrayExpression": "first" } option:

/*eslint indent: ["error", 2, {"ArrayExpression": "first"}]*/

var foo = [bar,
           baz,
           qux
];

ObjectExpression

Examples of incorrect code for this rule with the 2, { "ObjectExpression": 1 } option:

/*eslint indent: ["error", 2, { "ObjectExpression": 1 }]*/

var foo = {
    bar: 1,
baz: 2,
      qux: 3
};

Examples of correct code for this rule with the 2, { "ObjectExpression": 1 } option:

/*eslint indent: ["error", 2, { "ObjectExpression": 1 }]*/

var foo = {
  bar: 1,
  baz: 2,
  qux: 3
};

Examples of incorrect code for this rule with the 2, { "ObjectExpression": "first" } option:

/*eslint indent: ["error", 2, {"ObjectExpression": "first"}]*/

var foo = { bar: 1,
  baz: 2 };

Examples of correct code for this rule with the 2, { "ObjectExpression": "first" } option:

/*eslint indent: ["error", 2, {"ObjectExpression": "first"}]*/

var foo = { bar: 1,
            baz: 2 };

ImportDeclaration

Examples of correct code for this rule with the 4, { "ImportDeclaration": 1 } option (the default):

/*eslint indent: ["error", 4, { "ImportDeclaration": 1 }]*/

import { foo,
    bar,
    baz,
} from 'qux';

import {
    foo,
    bar,
    baz,
} from 'qux';

Examples of incorrect code for this rule with the 4, { "ImportDeclaration": "first" } option:

/*eslint indent: ["error", 4, { "ImportDeclaration": "first" }]*/

import { foo,
    bar,
    baz,
} from 'qux';

Examples of correct code for this rule with the 4, { "ImportDeclaration": "first" } option:

/*eslint indent: ["error", 4, { "ImportDeclaration": "first" }]*/

import { foo,
         bar,
         baz,
} from 'qux';

flatTernaryExpressions

Examples of incorrect code for this rule with the default 4, { "flatTernaryExpressions": false } option:

/*eslint indent: ["error", 4, { "flatTernaryExpressions": false }]*/

var a =
    foo ? bar :
    baz ? qux :
    boop;

Examples of correct code for this rule with the default 4, { "flatTernaryExpressions": false } option:

/*eslint indent: ["error", 4, { "flatTernaryExpressions": false }]*/

var a =
    foo ? bar :
        baz ? qux :
            boop;

Examples of incorrect code for this rule with the 4, { "flatTernaryExpressions": true } option:

/*eslint indent: ["error", 4, { "flatTernaryExpressions": true }]*/

var a =
    foo ? bar :
        baz ? qux :
            boop;

Examples of correct code for this rule with the 4, { "flatTernaryExpressions": true } option:

/*eslint indent: ["error", 4, { "flatTernaryExpressions": true }]*/

var a =
    foo ? bar :
    baz ? qux :
    boop;

offsetTernaryExpressions

Examples of incorrect code for this rule with the default 2, { "offsetTernaryExpressions": false } option:

/*eslint indent: ["error", 2, { "offsetTernaryExpressions": false }]*/

condition
  ? () => {
      return true
    }
  : () => {
      false
    }

Examples of correct code for this rule with the default 2, { "offsetTernaryExpressions": false } option:

/*eslint indent: ["error", 2, { "offsetTernaryExpressions": false }]*/

condition
  ? () => {
    return true
  }
  : condition2
    ? () => {
      return true
    }
    : () => {
      return false
    }

Examples of incorrect code for this rule with the 2, { "offsetTernaryExpressions": true } option:

/*eslint indent: ["error", 2, { "offsetTernaryExpressions": true }]*/

condition
  ? () => {
    return true
  }
  : condition2
    ? () => {
      return true
    }
    : () => {
      return false
    }

Examples of correct code for this rule with the 2, { "offsetTernaryExpressions": true } option:

/*eslint indent: ["error", 2, { "offsetTernaryExpressions": true }]*/

condition
  ? () => {
      return true
    }
  : condition2
    ? () => {
        return true
      }
    : () => {
        return false
      }

Examples of additional correct code for this rule with the 4, { "ignoreComments": true } option:

/*eslint indent: ["error", 4, { "ignoreComments": true }] */

if (foo) {
    doSomething();

// comment intentionally de-indented
    doSomethingElse();
}

Compatibility

  • JSHint: indent
  • JSCS: validateIndentation

Version

This rule was introduced in ESLint v0.14.0.

Resources

  • Rule source
  • Tests source

Понравилась статья? Поделить с друзьями:
  • Error expected identifier or before string constant
  • Error expected identifier or before numeric constant
  • Error execution failed with error code 1
  • Error expected for function style cast or type construction
  • Error expected expression before token что это