How to get prettier to add braces when missing on if/else
Asked Answered
C

2

21

I've googled for a while and not found how to do this. I have eslint and prettier setup in my project.

// What I have:
if (a == b) doSomething();

// What I want from either eslint or prettier
if (a == b) {
  doSomething();
}

Can any one show me how to get this done? Or show me their config that does this?

Cornerstone answered 6/1, 2019 at 19:54 Comment(0)
U
18

tl;dr : create a .eslintrc.json for your project and a rule for curly.

{
    "rules": {
        "curly": "error",
    }
}

Prettier only prints code. It does not transform it. This is to limit the scope of Prettier. Let's focus on the printing and do it really well!

Here are a few examples of things that are out of scope for Prettier:

  • Adding/removing {} and return where they are optional.
  • Turning ?: into if-else statements.
  • Sorting/moving imports, object keys, class members, JSX keys, CSS properties or anything else. Apart from being a transform rather than just printing (as mentioned above), sorting is potentially unsafe because of side effects (for imports, as an example) and makes it difficult to verify the most important correctness goal.
  • Turning single- or double-quoted strings into template literals or vice versa.

so to get what you want, you should use eslint. eslint has a --fix option and a rule for all, which would provide exactly what you want.

eslint for vscode.

configuration of eslint.

Hope this helps.

Uncork answered 7/1, 2019 at 2:10 Comment(6)
This is incorrect; prettier does transform code. For example, prettier --write .Abrahamsen
The docs say all is the default option but I did have to add it explicitly to enforce the rule in all cases (it didn't work for one-liners).Onepiece
@JohanMaes I'm having trouble understanding your comment; are you talking about eslint or prettier? what option?Inconvenient
@Abrahamsen so, prettier can add braces then?Inconvenient
@Inconvenient I had to add all to the ESLint rule to make it work: curly: ['error', 'all'].Onepiece
prettier --write . is a command to print same code a different way, it doesn't prove that it can transform it. However, prettier can add/remove trailing commas and round brackets (e.g. 3*3/2 or (a)=>a+1). I personally think that adding curly braces should not be considered a transformation either. But prettier maintainers seem to insist otherwise.Grier
T
1

To make this change programmatically and comprehensively throughout your code base, assuming your package.json looks something like this

{
  ...
  "scripts": { 
    ...
    "format": "prettier --write .",
    "lint": "eslint .",
  }
}

do this:

  1. update your .eslintrc.js just like the accepted answer suggests
{
    "rules": {
        "curly": "error",
    }
}
  1. npm run lint -- --fix
  2. npm run format
Tweeze answered 5/3 at 22:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.