How to do it…
Installing Prettier is very simple: you should just add the VSC extension, which you can find by searching for Prettier Code Formatter; as a check, the latest version (as of December, 2018) is 1.16.0, and the author is Esben Petersen. The plugin itself can be found in the VSC marketplace, at https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode. You can also install it globally (as we saw in the Installing packages for different purposes section earlier in this chapter) to be able to use it in scripts or from the command line with npm or yarn. See https://prettier.io/docs/en/install.html, and I'd recommend doing that.
There is one change you will want to make in the VSC preferences. Go to File | Preferences | Settings, and add the following line to your user configuration, so every file will be formatted automatically whenever you save it:
"editor.formatOnSave": true,
.
.
.
If you'd rather only apply Prettier to JS, then you should use this instead:
"[javascript]": { "editor.formatOnSave": true },
.
.
.
As we said, Prettier is pretty opinionated as to how code should look, and there are only a few options that you can change. The available options can be set in package.json (which makes it easier for all the team to share them) in a "prettier" key. Some of the possibilities (meaning the ones you might want to modify) are as follows:
Personally, the only ones I use are tabWidth:4 and printWidth:75, but the latter is for the sake of the book only, not for other work. My package.json thus includes the following; I have it just before the dependencies key, but you can place it elsewhere:
"prettier": {
"tabWidth": 4,
"printWidth": 75
},
.
.
.
You can also use Prettier independently of VSC, and in that case the configuration options should go in a .prettierrc file. See https://prettier.io/docs/en/cli.html and https://prettier.io/docs/en/configuration.html for more on this.
Finally, if you want to avoid Prettier code formatting for some reason or another, you can do the following:
- Avoid all formatting for a given file by adding its path and name to a .prettierignore text file at the project root
- Avoid reformatting a single sentence by preceding it with a // prettier-ignore comment
For the latter option, remember to use the appropriate comment style depending on the source code language. For example, in an HTML file's you would use <!-- prettier-ignore -->, while in CSS, it should be /* prettier-ignore */, and for JSX, {/* prettier-ignore */}.