How to set up Prettier and automatic formatting on VS Code

Prettier is a code formatter that makes your code look neat and consistent. Below is an easy way to set up Prettier on your VS Code and allow automatic formatting.

Step 1: Install Prettier

Click on the “extension logo” from the left sidebar and type “Prettier” in the search bar. Next, click on the “Install” button.

Installing prettier in the VS code
Installing prettier in the VS code

Once found, click on it to proceed to installation.

Step 2: Set autosave

Once installation is successful, open the settings of your VS Code. You can do this on Windows by pressing both Ctrl and ,. Click on the formatting section of the Text Editor tab and enable Format on Save Mode.

Enabling format on save mode
Enabling format on save mode

Step 3: Format your code

Now, highlight your code and right-click. Select Format Document.

Select "Format Document" from the menu
Select "Format Document" from the menu

Once you click on Format Document, a dialog box will tell you to configure your code formatter. This is to set your default code formatter. Click on the configure button.

Click on the "configure" button
Click on the "configure" button

Step 4: Select Prettier as the default

After you click on configure, select Prettier as the default formatter.

Selecting Prettier as the default formatter
Selecting Prettier as the default formatter

And that’s it!

Now, your code should be formatted with Prettier anytime you save your file.

Hands-on practice

Below, you can find a working version of VS Code, in which you can install Prettier and format the code.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JFrame implements ActionListener {
	private JLabel labelQuestion;
	private JLabel labelWeight;
	private JTextField fieldWeight;
	private JButton buttonTellMe;
	public Main() {
		super("Water Calculator");
		initComponents();
		setSize(Toolkit.getDefaultToolkit().getScreenSize());
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	private void initComponents() {
		labelQuestion = new JLabel("How much water should a person drink?");
		labelWeight = new JLabel("My weight (kg):");
		fieldWeight = new JTextField(5);
		buttonTellMe = new JButton("Tell Me");
		setLayout(new FlowLayout());
		add(labelQuestion);
		add(labelWeight);
		add(fieldWeight);
		add(buttonTellMe);
		buttonTellMe.addActionListener(this);
	}
	public void actionPerformed(ActionEvent event) {
		String message = "Buddy, you should drink %.1f L of water a day!";
		float weight = Float.parseFloat(fieldWeight.getText());
		float waterAmount = calculateWaterAmount(weight);
		message = String.format(message, waterAmount);
		JOptionPane.showMessageDialog(this, message);
	}
	private float calculateWaterAmount(float weight) {
		return (weight / 10f) * 0.4f;
	}
	public static void main(String[] args) {
		new Main().setVisible(true);
	}
}
Format the code using Prettier in VS code