others-How to solve the prettier not working problem when using vscode with prettier ?

1. Purpose

In this post, I would demo how to solve the issue that prettier not formatting our js code when saving in vscode.

2. Environment

  • Node.js v12.14.0
  • npm 7.11.2

3. The solution and reason

3.1 The background knowledge

What is prettier?

Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary

It support to format such languages:

What’s the differences between prettier and linter?

Prettier are for formatting and linters are for catching bugs!

How to install prettier? You can just follow this link to install it or just install it as follows:

$ npm install --save-dev --save-exact prettier

And install it in vscode, click extensions on the left sidebar of vscode, and input prettier to search for the plugin:

image-20210715145407338

Click install button at the right of the pane, and you are done.

3.2 The problem

Now when I try to change the code in vscode, and save it, I hope prettier would help me to format the code automaticcally. But nothing happens!!!

The below picture shows the failed formatting result of my code. It should help me to format from line 7 to line 9.

image-20210715145542480

3.3 The solution

First, We should set the default formatter in vscode, just open code-->preferences-->settings of vscode, and input default formatter in the right pane to search for the setting, just as follows:

image-20210715105847442

Second, we should enable the format-on-save-mode, goto settings, and find Text editor-->Formatting setting, and check the format on save checkbox, just as the below picture shows:

image-20210715105817731

Now let’s test the prettier magic: (I tried to mess up the code format, andt then click to save the code.)

xcode_prettier_1

It works!

4. Summary

In this post, I tried to demo how to solve the prettier issue in vscode, the key point is to set prettier as the default formatter in vscode, and enable format-on-save setting in vscode.