How to use Prettier with JavaScript

Introduction

Prettier is a development tool used to format your JavaScript / TypeScript code to conform to a standard style consistent across JavaScript apps. This tool will automatically format the code across your codebase, also you can run a check command to verify all files are formatted which is useful for running tests before deployments.

How to setup

Use the Node package manager to install prettier with the following command.

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

To create a .prettierrc file use the command below, this will allow you to configure the options for the tool.

node --eval "fs.writeFileSync('.prettierrc','{}\n')"

Create a .prettierignore file using the command below, this is useful if you want to ignore certain files when running it.

node --eval "fs.writeFileSync('.prettierignore','# Ignore artifacts:\nbuild\ncoverage\n')"

One thing to keep in mind is if the .gitignore file exists prettier will read and ignore the files/folders in this file as well.

How to use

Here are the basic commands that would mostly be used with this tool.

To run a check on all files use the following command.

npx prettier . --check

To format all files use the following command.

npx prettier . --write

Conclusion

Prettier is popular as it gets around 30 million downloads according to the npmjs page. As it is commonly used it makes sense to stick to a standardized coding style that the majority of programmers would be familiar with as opposed to your custom style plus it would make working in a team easier since each other's code would become easier to read.