Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get prettier to add braces when mssing on if/else

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?

like image 723
Arnold Rimmer Avatar asked Jan 06 '19 19:01

Arnold Rimmer


1 Answers

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.

like image 122
Yedhin Avatar answered Oct 26 '22 12:10

Yedhin