18

I'm using prettier in VSCode on a react native project and it removes parentheses in mixed operators or when declaring a var with a parenthesis. How to prevent prettier from doing that

example1:

 const foo = (a && b) || c;

After:

const foo = a && b || c;

example2

const c = (a.toString()).toUpperCase();

After:

const c = a.toString().toUpperCase();

I know that in most cases it doesn't change the logic but I want to disable this feature.

  • 3
    This seems pretty fundamental... I don't want a code formatter to change my application logic... Any update on this? – Bryson Kruk Oct 04 '21 at 15:44
  • 3
    I was looking into this same feature and found an open ticket on the issue but still seems to be no configuration option available yet https://github.com/prettier/prettier/issues/187 – David Rachwalik Jan 06 '22 at 02:45
  • 3
    @BrysonKruk it should not "change the logic" there are some order rules in each programming language. **However I do agree this is a very bad behavior** and should not be allowed by default. There is also an opened issue around the same thing for ternary operators - https://github.com/prettier/prettier/issues/3805 – jave.web Apr 10 '22 at 09:05

2 Answers2

6

You can use “prettier-ignore” comments to ignore parts of files. Like // prettier-ignore

Here you have a link to documentation: https://prettier.io/docs/en/ignore.html

KeltoRino
  • 69
  • 1
  • 2
  • 2
    This works, but I recommend to double check if you really need it. I had a case where I first thought prettier is changing the meaning of my expression by removing the brackets, so it would return something unintended. But then discovered that – of course – it didn't and I was the one that had an error in the expression. So it's good to assume that prettier is doing it right, and only use this to preserve purely visual deviations in the formatting, never logical ones. There might be exceptions, but then it would be good to file a bug report, I guess. – Wu Wei Jun 10 '22 at 08:00
-6

You can config it in the settings.json and add "prettier.bracketSpacing", please read here

You can also use eslint more customizable and can use different code style like airbnb ...