简体   繁体   中英

How do I prevent code wrapping in Prettier / ESLint

I am struggling to find a setting in my Prettier / ESLint config which allows me to wrap my code like this:

var [
  first,
  second,
  third,
  etc,
] = data();

When I hit save, it always turns the code to this automatically:

var [first, second, third, etc] = data();

This may not be such a big problem with this simple demonstration, but with more complex destructuring, this one liner will get hard to read.

Thank you for your help!

Prettier will overwrite whatever eslint does anyways, so using eslint for this won't really help you if you also have prettier in a project (prettier should also be run after eslint). Prettier doesn't have any way to control what you're asking, there have been several github discussions on multiline styling but they usually don't go anywhere because of good reasons.

Prettier will wrap arrays or objects according to the print width, so if you have a small array of things like resolves in webpack:

resolves: ['.tsx', '.ts', '.jsx', '.js']

Prettier will write it to a single line because writing that in a multiline looks really stupid. The same goes for anything similar like jest extensions or plugins where there's a single entry in the whole array like plugins: ["react"] , which again would look really stupid putting that on a multiline just because of a single entry.

Prettier will however wrap it as soon as the items take up more than the print width, which is by default 80. For me this is really the way it should be, I don't want a bunch of 4 character multilines, it looks way neater when it's wrapped up in a sideways array, while when the items inside is longer it also perfectly multilines it.

Code like this:

var [
  first,
  second,
  third,
  etc,
] = data()

Looks really bad, it belongs on a single line. Perhaps prettier should support multiline just so people can customize their stuff, but I'd never allow code like this on my project.

That being said you can do:

var [
  first,  //
  second,
  third,
  etc,
] = data()

And it will prevent prettier from one line styling it, but IMO you shouldn't be using it.

In Eslint, you can enforce line breaks between array elements using option array-element-newline :

Incorrect code:

/*eslint array-element-newline: ["error", "always"]*/
var d = [1, 2, 3];

Correct code:

/*eslint array-element-newline: ["error", "always"]*/
var d = [1,
    2,
    3];

You can also check out:

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