Search code examples
reactjsvisual-studio-codeprettier

Prettier not working on save from within Visual Studio Code


It appears the formatting via keyboard and formatting from the menu are not on the same page, but I don't know why. Below are my exact detailed steps...

From Visual Studio Code 1.75.1

  • I installed the extension Prettier - Code formatter v9.10.4
  • From File -> Preferences -> Settings, I typed in default format and set it to Prettier - Code format

enter image description here

  • Again from File -> Preferences -> Settings, I typed in format on save and checked the box.

enter image description here

Now from within my ReactJs project workspace, I have the following file with code example:


import React from "react";

import ChartBar from "./ChartBar";
import "./Chart.css";

const Chart = (props) => {
  return <div><div> do something </div><div> do something </div><div> do something </div></div>;
};

export default Chart;

When I click Ctrl + S, it doesn't change anything.

But if I right click on the window and select Format Document with, and select Prettier Code Formatter it corrects the format to the following...

import React from "react";

import ChartBar from "./ChartBar";
import "./Chart.css";

const Chart = (props) => {
  return (
    <div>
      <div> do something </div>
      <div> do something </div>
      <div> do something </div>
    </div>
  );
};

export default Chart;


Also, from within my workspace, I generated a .vscode folder with a settings.json file, with the following settings...

{
  "editor.defaultFormatter": "esbenp.prettier-vscode"
}

Still no fix.

Why can't I get my Format on Save to work exactly as clicking on the menu option???

Update

I finally figured it out. In addition to my settings above, I also needed to updated my workspace settings.json file with the following code:

{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

All good now!


Solution

  • In VSCode, hit CTRL + SHIFT + P, write Preferences: Open User Settings (JSON) and hit enter, it will open up your settings.json:

    Make sure prettier is your default formatter:

    "editor.defaultFormatter": "esbenp.prettier-vscode"
    

    you can set it for specific languages e.g: for typescript:

    "[typescript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },