简体   繁体   中英

Is there a way to break lines for all chained methods only if more than two?

I have some methods like:

// 1. two methods chained
first.method().anotherMethod();

// 2. three or more
second.method().anotherMethod().yetAnotherOne();
third.method().anotherMethod().yetAnotherOne().stillGoing();

First type is ok, may stay that way. But I want to know if is possible for the second type to break a line for all methods, like:

// 1. two methods chained
first.method().anotherMethod();

// 2. three or more
second.method()
  .anotherMethod()
  .yetAnotherOne();

third.method()
  .anotherMethod()
  .yetAnotherOne()
  .stillGoing();

Eslint have the rule newline-per-chained-call but it won't force the behavior I want.

{ "ignoreChainWithDepth": 2 } will let me do this:

second.method().anotherMethod()
  .yetAnotherOne();

third.method().anotherMethod()
  .yetAnotherOne()
  .stillGoing();

And well, it's not ideal.

Is there a way to manage it?

I've tried newline-per-chained-call with the { "ignoreChainWithDepth": 2 } option, and looking for plugins. Did not find any plugin for it.

You can use the array-element-newline rule in ESLint to enforce line breaks for long chains of methods. In.eslintrc

{
  "rules": {
    "array-element-newline": ["error", { "multiline": true, "minItems": 3 }]
  }
}

This rule is typically used to enforce line breaks in arrays, but it can also be used to enforce line breaks in chains of method calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM