简体   繁体   中英

Prettier re-formatting single line `if` statements causing eslint errors: why?

I am hoping to run Prettier on an existing codebase that is also using eslint.

There are many places where single-line if s exist and I want to leave them intact, but Prettier keeps changing them to multi-line without braces, which of course causes an error.

It's going from: if (...) throw new Error(...)

To:

if (...)
  throw new Error(...)

What is the magic combination of rules to let Prettier ignore these?

You are using bracketless if statements. You also forgot the semicolons. Bracketless if statements are unreliable. Adding braces after will get rid of your problem:

if (...) {
   throw new Error(...);
}

This also works:

if (...) {throw new Error(...);}

You need to change your maximum allowed line length, the default is 80. That's the only reason Prettier would wrap your bracketless if to multiple lines. The intended behavior is that if statements without brackets are on single line: GitHub Issue .

You can change the max line length in your .prettierrc file:

{
    "printWidth": 80
}

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