We all want higher-quality code. With Prettier, you can achieve this with minimal effort.
If you enjoy this tutorial, please give it a 💓, 🦄, or 🔖 and consider:
- signing up for my free weekly dev newsletter
- subscribing to my free YouTube dev channel
What is Prettier?
Prettier is an opinionated code formatter that supports various languages. When applied to a supported file type, Prettier will automatically format the code in that file.
Supported Languages
Currently, Prettier supports a bunch of different languages/frameworks on its own and also has community plugins for other languages.
Supported By Prettier
- JavaScript
- JSX
- Flow
- TypeScript
- JSON
- HTML
- Vue
- Angular
- CSS
- Less
- SCSS
- GraphQL
- Markdown/MDX
Supported By Prettier Plugins
- Java
- PHP
- PostgreSQL
- Ruby
- Swift
- TOML
- XML
The Power of Format on Save
There are a couple different ways you can use Prettier:
- Using the command line interface (CLI) to format individual or groups of files
- Setting up your code editor/IDE to format files automatically (e.g., when you save a file).
I prefer automatically formatting on save because it immediately gives you feedback. One of the most important pieces of feedback it gives you is it won't format if you have a syntax error! This is actually incredibly powerful. When you're in the flow of programming, it's critical to have different types of immediate feedback to let you know when you've made a mistake so you can quickly correct course. Prettier offers one of the quickest feedback loops that exists.
Installing Prettier
Okay, enough of me gushing about the greatness of Prettier, let's start using it in an example.
Quick Caveats About This Example
- You can install Prettier globally, but it's advised to install it locally in your project as a development dependency. That way, all developers will have it at the same version.
- This example assumes your project dependencies are managed by
yarn
ornpm
. - This example assumes you're using VS Code, which is how we'll configure our "Format on Save" functionality. Other development environments likely have similar functionality, you just might have to look it up!
Step 1: create a new project directory
Let's create a project directory for our new project. I'm running these commands in bash but you can create new files and folders using whatever method you're comfortable with.
mkdir prettier-example
Step 2: initialize yarn (or npm)
Next, we initialize a new project. If using yarn, simply run the yarn
command:
yarn
If using npm, run the following command to initialize with the default configuration:
npm init -y
Step 3: Install Prettier
Now we install Prettier. Make sure to pin Prettier to an exact patch version! Prettier can update their formatting preferences between patch versions, so pinning to a specific patch version prevents formatting differences between different developers.
Also, make sure to install Prettier as a dev dependency since it's a dev tool rather than something used in production.
Using yarn:
yarn add -D prettier@2.0.5
Or npm:
npm install --save-dev prettier@2.0.5
Let's also create an empty prettier configuration file in our directory. Create .prettierrc.json
and just put an empty object in there:
.prettierrc.json
{}
Install the Prettier Plugin for VS Code
Make sure to install the Prettier plugin for VS Code. Instructions can be found here.
Step 4: Create a poorly-formatted file
Let's create a poorly formatted file. Make index.js
in your project directory and put the following code in it:
function greet (){
const myVar= 'hello'
console.log(myVar)}
This snippet has all sorts of weird spacing.
Step 5: Set VS Code to format on save
Go to Settings in VS Code. You can find this under File > Preferences > Settings or you can just use the ctrl+comma shortcut (cmd+comma on Mac). Find the Editor: Format On Save option and make sure it's checked.
Note: Other editors should be able to format on save as well, you will just have to find some editor-specific instructions if you're not using VS Code.
Step 6: Save your index.js file
Save your index.js
file. If all goes well, your file should format correctly!
function greet() {
const myVar = "hello";
console.log(myVar);
}
Note that our spacing looks correct. Additionally, Prettier added trailing semi-colons and changed our single quotes to double quotes. A lot of this is configurable in our .prettierrc.json
file if you don't like some of the changes!
A More Impressive Example
Let's change our index.js
file to have some really gnarly code. Try changing it to this:
const navBarProps = {name:["John Doe", null],
displayMode: ["dark", "light"],timezone: ["ET", "CT", "MT", "PT"],
};
function allCombinations(obj) {let combos=[{}];
for(const[key, values] of Object.entries(obj)) {combos = combos.flatMap((combo) =>
values.map((value) => ({ ...combo, [key]: value })));}return combos;}
console.log(allCombinations(navBarProps));
That's really quite ugly. Now save the document.
const navBarProps = {
name: ["John Doe", null],
displayMode: ["dark", "light"],
timezone: ["ET", "CT", "MT", "PT"],
};
function allCombinations(obj) {
let combos = [{}];
for (const [key, values] of Object.entries(obj)) {
combos = combos.flatMap((combo) =>
values.map((value) => ({ ...combo, [key]: value }))
);
}
return combos;
}
console.log(allCombinations(navBarProps));
Beautiful!
Why This is So Important
Prettier helps you write more consistent code. You see patterns better when your code is formatted correctly. When your code doesn't format on save, you start immediately recognizing when your code has errors.
Please consider using Prettier, it'll make your dev process much more enjoyable!
Top comments (16)
Hey, Nick.
Nice article. Very simple and straightforward. Although I think that you may have missed an important step, or maybe I am doing something wrong here 😕
The steps didn't work for me until I installed the Prettier extension:
marketplace.visualstudio.com/items...
Is this missing in the steps or am I doing something wrong?
Thanks!
Oh goodness I think you’re right. I’m going to update the instructions now. So sorry and thank you for finding that.
You're welcome! 😊
Always happy to contribute in the best way.
Having an IDE to automatically format code really reminds me of why QBASIC was so great for beginners: because beginner programmers can't be trusted to format their code nicely.
But keep in mind, the formatting of the code has nothing at all to do with code quality. One could have a horrible bunch of crap using what people consider "pretty" syntax. One could also write a very elegant algorithm written with what you consider "ugly" syntax. Whether it be snake case, camel case, all uppercase, or all lowercase, two indents, four indents, tabs, spaces, braces on the same line, braces on different lines, semicolons here or there ... it's very subjective, and it makes absolutely no difference to what is real code quality. I've seen coding horrors that were "beautifully" written. (beautifully, as in: very strictly following a particular set of syntax formatting rules.)
Yes, I would agree. Although it is opinionated about a lot of things, I felt in a way those rules mostly make sense and hence I adopted to those rules and it helps.
Listen, I like Prettier and I use it in my JavaScript projects.
But I will NEVER use it for Ruby. I'm sorry lmao
I didn't even know you could do that until I read this!
About the only thing you can configure in Prettier is "no semicolons" and 'single quotes'!
We have both of those turned on for our React project.
Heh, prettier is pretty darn opinionated. I remember requesting the ability to configure something on their GitHub issues and got shot down. Ultimately, the consistency is far more important to me than having it one particular way or another.
Ah I'm going back to the linting wars my team had in 2019.
"Husky! That's just a backdoor to Prettier"
Forward 12 months - it was true, and boy am I happy.
This is basic IDE functionality, even for Javascript. Is there really a need for third party tool to do this?
What ide do that?
Format code? Netbeans, Jetbrains, all the big ones I think. You can usually set custom rules for formatting per language, and even per language per project.
That's why I prefer using the linter as code formatter instead of installing another package. This way I only have to write one set of rules once.
How does it compare to using StandardJS tools?
In go, the formatter aligns the key value pairs vertically and I am missing this in JS. If anyone knows a formatter that does this, please shout. LOUDLY.