14

The ESLint rule for indent allows for you to specify which nodes are ignored, when determining whether the rule should apply to that node, using the ignoredNodes option.

I've got the following code that I want to ignore with this rule:

const a = b
  ? `c${
      d
    }`
  : e

Specifically, the line with d and the subsequent line are reported as having two more spaces than they should. I want to ignore those lines from the rule, but I can't figure out the node that should apply.

Node types are specified in this repo. I know that ternary expressions, like used in this code, is a ConditionalExpression node, and it seems like a template literal node exists, but I can't get it to work.

I know I can use eslint-disable-next-line, eslint-disable, etc., but I don't want to use those, because then I'd have to use them every time this comes up.

Gary
  • 3,465
  • 5
  • 32
  • 56

2 Answers2

14

From looking at an ast tree with simply ${foo}, I confirmed that it is truly the TemplateLiteral node. However I happened to also know the solution from there: you need to select its children as well. This can be done with TemplateLiteral > *. The reason why your solution wasn't working is because ESLint will exempt the TemplateLiteral from the indent rules, but only the little ${ and } parts, not the contents.

This can go into your ESLintrc file as such:

"indent": ["error", "tab", { "ignoredNodes": ["TemplateLiteral > *"] }]

I'm sorry no one else was able to answer your question sooner.

David Archibald
  • 1,296
  • 13
  • 26
  • 1
    I got a warning from eslint using this config, specifically since it expects `ignoredNodes` to be an array. The following fixed it for me: ```js "indent": [{ "ignoredNodes": ["TemplateLiteral > *"] }] ``` – Michael Oliver Jan 30 '19 at 21:09
  • I didn't get that warning. I've fixed that now. – David Archibald Jan 31 '19 at 04:32
  • It overwrites extended rules for `ignoredNodes`. Can we just extend this array, without overwriting? – B. Bohdan Jan 14 '20 at 10:30
  • The rule had the wrong syntax, it needed the first 2 parameters (`"error", "tab"`). Now it works without errors – fregante Mar 17 '20 at 09:57
8

To ignore all indentation and newline errors in ESLint inside a template literal, including function calls or deeply nested JS syntax, you can use "ignoredNodes": ["TemplateLiteral *"] (without the > child selector, to target all descendants.)

  "rules": {
    "indent": ["error", 2, { "ignoredNodes": ["TemplateLiteral *"] }],
    "function-paren-newline": "off"
  }

You also have to specify your normal indentation rule, e.g. "error", 2 for enforcing 2 spaces or "error", "tab" for tabs.

"function-paren-newline" was also giving errors inside my template literals, I also wanted to disable that (because I'm extending an existing ESLint config that displayed an error for that).

Maarten ter Horst
  • 2,497
  • 1
  • 14
  • 10