Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VSCode Prettier Extension vs Command Line Prettier

I have an issue where HTML file formatting in VSCode, "on-save", is different than Prettier's formatting when using the command line.

My user settings (changing these values doesn't seem to make any difference):

{
    "[html]": {
        "editor.formatOnSave": true
    },
    "prettier.eslintIntegration": false,
    "html.format.enable": false
}

When I run Prettier from the command line, my HTML gets formatted like this:

prettier --write "./src/app/my-file.html"

my-file.html:

<a ng-hide="$last" href="" ng-click="doThis(thing)"
  >{{ crumb.title }}</a
>

The same code when I save the file in VSCode (allowing the Prettier extension to do the formatting):

<a ng-hide="$last" href="" ng-click="doThis(thing)">{{
  crumb.title
}}</a>

I know the extension is installed and working, because I see this icon in the bottom right hand side of the screen:

enter image description here

And, when I hover over this icon, I see a tooltip that says [email protected], the same version I have installed on the command line prettier -v

Why am I getting different results with these 2 methods? I have not altered any settings, other than the above

like image 584
Pop-A-Stash Avatar asked Feb 14 '19 21:02

Pop-A-Stash


People also ask

What does the Prettier extension do?

Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.

How do I run Prettier from command line?

Use the prettier command to run Prettier from the command line. To run your locally installed version of Prettier, prefix the command with npx or yarn (if you use Yarn), i.e. npx prettier --help , or yarn prettier --help . To format a file in-place, use --write .

How do you run Prettier in VS Code terminal?

We will start by installing the Prettier extension for VS Code. Once you have installed it, you can use it with CTRL + CMD + P (MacOS) or CTRL + Shift + P (Windows) to manually format a file or a selection of code.


1 Answers

I needed to create a .prettierrc file with the following contents:

{
  "overrides": [
    {
      "files": "*.html",
      "options": {
        "parser": "html"
      }
    }
  ]
}

The command line was using the html parser, while VSCode was using the angular parser. This way they are both using the same parser for .html files.

like image 154
Pop-A-Stash Avatar answered Oct 20 '22 11:10

Pop-A-Stash