Why does Prettier not format code in VS Code?

Javascriptvue.jsVisual Studio-Codenuxt.jsPrettier

Javascript Problem Overview


In my Nuxt application where ESlint and Prettier are installed and enabled, I switched to Visual Studio Code.

When I open a .vue file and press CMD+ Shift + P and choose Format Document, my file does not get formatted at all.

My .prettierrc settings:

{
  "tabWidth": 2,
  "semi": false,
  "singleQuote": true
}

I have so many source code lines, so I cannot format them manually. What am I doing wrong?

Javascript Solutions


Solution 1 - Javascript

How I've sorted it after having super huge frustrations with Prettier stopping working in VSCode.

  1. Select VS Code -> View -> Command Palette, and type: Format Document With
  2. Then Configure Default Formatter... and then choose Prettier - Code formatter.

This sorted the problem for me magically.

Depending on your case this might help you...

Solution 2 - Javascript

If doing what @Simin Maleki mentioned does not solve it for you, there is a chance that your default formatter is not set:

File > Preferences > Settings > Search for "default formatter" 

Make sure your Editor: Default Formatter field is not null but rather esbenp.prettier-vscode and that all the languages below are ticked. This fixed my issue.

STEP BY STEP WALKTHROUGH

Steps to enable default formatter

Also make sure that your format on save is enabled:

Format on save check

Solution 3 - Javascript

Sometimes, prettier stops working when there are syntactic errors in the code. You can view the errors by clicking on the x button on the bottom right corner beside Prettier

enter image description here

Solution 4 - Javascript

Prettier could also format your files on save.

However, installing and enabling does not result in working.

You have to check "format on Save" in VSCode: Setting >> User >> Text Editor >> Formatting

enter image description here

Solution 5 - Javascript

disable and enable prettier extension solves my problem

Solution 6 - Javascript

You only have to configure your Default Formatter and check the checkbox in Format On Save in the settings, after installing prettier to make it work. Don't mess with other configuration files.

1 - Select Default Formatter

  1. Open Files -> Preferences -> Settings (or Ctrl + , in Windows).
  2. Search for Editor: Default Formatter
  3. Select your default formatter as Prettier - Code Formatter;

See the image below;

Default Formatter Capture

2 - Save On Format

  1. Open Files -> Preferences -> Settings (or Ctrl + , in Windows).
  2. Search for Editor: Format on Save
  3. Click the check box under Format On Save;

See the image below;

Format On Save Capture

Solution 7 - Javascript

I am not using Vue, but had the same problem.

I already had the settings

  • Editor: default formatter to prettier
  • Editor: Format on Save to true
  • I already had .eslintrc.js and .prettierrc files But nothing worked.

The solution to my problem was that I had all set properly, except I needed to:

  • Command + Shift + p
  • type format document with
  • select Configure Default Formatter...
  • select Prettier as default.

I don't know why the Editor: Format on Save set to true was not enough. I needed to select default formatter using the above steps so it worked.

enter image description here

Solution 8 - Javascript

can you try to add this section to your VS Code settings.json file?

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

Solution 9 - Javascript

I faced this problem and these three steps solved my problem: Prettier Doesn't format code

Solution 10 - Javascript

you can still have issues in spite of all these settings. In this case, as pointed out in an earlier answer, then it would be a good point to check the prettier notification at bottom status bar in VSCode.

enter image description here

When clicking on that status, the output panel should report the issue in the HTML file. For me, the issue was I had a div inside a p tag which I assume prettier/VSCode conventions are against. When I removed it (and combined with all the settings above, namely default formatter and format on save) I got prettier working.

.prettierrc is not required unless you want to override VSCode settings

Solution 11 - Javascript

This is not a problem with Prettier itself, but prettier-vscode, the VSCode extension. According to its documentation, Vue formatting is disabled by default:

> prettier.disableLanguages (default: ["vue"]) > > A list of languages IDs to disable this extension on. Restart required. Note: Disabling a language enabled in a parent folder will prevent formatting instead of letting any other formatter to run

In this case, to enable you should set "prettier.disableLanguages": []. And since this is an extension configuration, you should do it in VSCode settings file, not .prettierrc.

Solution 12 - Javascript

On Windows:

We can open the below file using:

Start > Run 

File Path:

%AppData%\Code\User\settings.json

Change From:

"[javascript]": {
    "editor.defaultFormatter": "vscode.typescript-language-features"
},

To:

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

Note:

Solution 13 - Javascript

For me the problem was with HTML files where formatting stopped working one day. I had Format On Save configured, which worked in all files except HTML.

I then realized that I experimentally set Format On Save Mode to modification instead of file and forgot about it. This had an effect of not formatting anything in HTML files, surprisingly not even my changes. Setting it back to file solved the issue.

enter image description here

Solution 14 - Javascript

1 .Use the other extension prettier was not working for me i just use the other VSCODE extension named PrettierNow i think this will help, done for me.Checkout the extension here

2 .From Latest Updates of prettier you need to add .prettierrc file in your root of the projects if you want to stick with prettier. An example of .prettierrc is this-

{
  "tabWidth": 4,
  "singleQuote": true,
  "semi": false
}

Solution 15 - Javascript

Enabling "format on Save" in VSCode: Setting >> User >> Text Editor >> Formatting worked for me! 

Print

Solution 16 - Javascript

If Prettier formats all other files except HTML files automatically on save:

Press Cmd + P or Ctrl + P to open the command palette and type the following text in it:

> open settings

Click on Preferences: Open Settings (JSON) from the suggestion dropdown. Inside the settings.json file, Check if "[html]" key exists. If the key exists and its value indicates using another formatting extension installed in Visual Studio Code, you should reset it back to use Prettier.

"[html]": {
    "esbenp.prettier-vscode"
}

For an instance, sometimes, the value of "[html]" key could be "remimarsal.prettier-now" when you would have Prettier Now extension installed.

If you don't have any other formatting extension installed other than Prettier, you can also remove the "[html]" key altogether from settings.json file.

Solution 17 - Javascript

This is what worked for me (my default formatter was already set to Prettier)

  1. Change default formatter to default
  2. Restart vscode
  3. Change default formatter back to Prettier.

Solution 18 - Javascript

Go to Manage(located on left-bottom corner) -> Settings -> Users tab -> Text-Editor -> Formatting -> check the format on save

if not working then close and again open your vscode editor

Solution 19 - Javascript

For me - it was to do with ESlint which also works with Prettier. Eslint wasn't working (a local installation vs global installation conflict) which broke Prettier.

Solution 20 - Javascript

Recently I got the same problem, that Prettier does not format code automatically on saving. Checking Prettier, I saw an error: Invalid "arrowParens" value. Expected "always" or "avoid", but received true.

The error message was seen when I clicked this: enter image description here

It turned out that I have Prettier Now installed also. This has a boolean value in my config file. After uninstalling Prettier Now, everything works fine.

Solution 21 - Javascript

Some times with auto plugins update Required files used by Prettier might go missing .

Check this path if files are present here or folder is empty

C:\Users\YOURUSERNAME\.vscode\extensions\esbenp.prettier-vscode-2.2.2\out

If missing uninstall and reinstall prettier

Solution 22 - Javascript

If none of the other answers work, check that a conflicting prettier config .prettierrc does not exist in your working directory or check for .prettierignore to be sure the files/folders are not being ignored.

Solution 23 - Javascript

Check if there is a .vscode/settings.json file in your project directory (workspace). In my case someone had checked in this file:

{
  "editor.formatOnSave": false
}

Solution: Delete the file (delete it from source control too) and add .vscode/ to .gitignore (if you're using git).

Solution 24 - Javascript

In my case it turned out I had configured prettier to use a configuration file that didn't exist (see screnshot below). That was hard to find since there wasn't any error message but prettier just didn't work. Maybe this helps somebody, too.

Screenshot

Solution 25 - Javascript

I Rolling back prettier to 1.7.3 and fixed it

Solution 26 - Javascript

In my case I had to do the following:

  1. Install prettier from the command line(npm install --save-dev --save-exact prettier prettier-plugin-custom)
  2. Reload VSCode

and voilà, everything started working.

TIP: To make sure the installation is good I checked for the version:

npx prettier --version

Solution 27 - Javascript

Check for requirePragma in .prettierrc, it says you need to add a top level comment for that file to be formatted

remove that rule and it should work

Solution 28 - Javascript

In some cases where prettier is provided as a dependency, you might need to install it before prettier vscode recognizes it using one of the following commands, depending on the package manager you are using
npm i or yarn

Solution 29 - Javascript

How to format your code through VScode's ESlint plugin

Alright, rather than giving a guide on how to use VScode's Prettier extension, I'd rather explain how to rely on ESlint and have both worlds: checking that your code is correct (ESlint), then formatting it (Prettier).

What are the advantages of this?

  • not forcing your entire team to use VScode with the Prettier extension, maybe some prefer Vim, IntelliJ's Webstorm, Emacs etc... A tool-agnostic solution is IMO always better.
  • I think that linting your code is more important that formatting it, but if you have both extensions working at the same time, you may have conflicts between the formatting and the linting.
  • your hardware will struggle less, if you have less extensions running (mainly because it can stop the conflicts)
  • using an ESlint + Prettier combo will strip the need to have a specific personal configuration aside of the codebase (untracked). You'll also benefit from having Vue/Nuxt specific ESlint rules and a simpler/more universal configuration.
  • an ESlint configuration can be configured to be run before a commit, in a CI/CD or anywhere really.

How to achieve this kind of setup?

Let's start first by installing the ESlint extension and only it, DO NOT install the Prettier one.

enter image description here

Not installed Vetur yet?

I do heavily recommend it for Vue2 apps (what Nuxt is running as of today), you can find it below. It will allow to quickly and simply ESlint (+ Prettier) any .vue files.


When it's done, access the Command Palette with either ctrl + shift + p (Windows/Linux) or cmd + shift + p (Mac) and type Preferences: Open Default Settings (JSON)

enter image description here

There, you should have something like this

{
  "workbench.colorTheme": "Solarized Dark", // example of some of your own configuration

  "editor.codeActionsOnSave": {
    "source.fixAll": true,
  },
  "eslint.options": {
    "extensions": [
      ".html",
      ".js",
      ".vue",
      ".jsx",
    ]
  },
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact",
    "html",
    "vue",
  ],
}

How to try that your configuration is now working?

To see if my solution is working, please download this Github repo, get the latest stable Node version (eg: 14) and run yarn to have it working. Otherwise, simply open VScode.
This repo can also be used to double-check that yours is properly configured by inspecting my files there!

Then, you could access any .js or .vue file and see the problems there (Command Palette: Problems: Focus on Problems View). nuxt.config.js and /pages/index.vue are good examples, here is the index.vue file.

enter image description here

You can see that we do have several things that can be fixed by Prettier but that we do also have an eslint(vue/require-v-for-key) error. The solution is available as a comment just below btw.

PS: if you want to have inline ESlint warnings/errors as in the screenshot, you can install Error Lens, it's a super amazing extension if you want to get rid of errors.

Save this file and you should saw that every auto-fixable things are done for you. Usually it's mainly Prettier issues but it can also sometimes be ESlint too. Since we do have the ESlint rules from Nuxt, you'll get some nice good practices out of the box too!

Tada, it's working! If it's not, read the section at the end of my answer.

If you want to create a brand new project

You can run npx create-nuxt-app my-super-awesome-project and select few things there, the most important being Linting tools: Eslint + Prettier of course (hit space to opt-in for one of them).

enter image description here

Warning: as of today, there is an additional step to do to have ESlint + Prettier working properly as shown in this Github issue. The fix should be released pretty soon, then the configuration below will not be needed anymore!

To fix this, run yarn add -D eslint-plugin-prettier and double check that your .eslintrc.js file is a follows

module.exports = {
  root: true,
  env: {
    browser: true,
    node: true
  },
  parserOptions: {
    parser: '@babel/eslint-parser',
    requireConfigFile: false
  },
  extends: [
    '@nuxtjs',
    'plugin:prettier/recommended', // this line was updated
    'prettier'
  ],
  plugins: [
  ],
  // add your custom rules here
  rules: {}
}

Then, you can have it working totally fine as above. Save the file and it should run ESlint then Prettier one after the other!


If you still have some issues
  • try to use the Command Palette again and ESLINT: restart ESLint Server or even Developer: Reload Window
  • feel free to leave a comment or contact me if you need some help

Solution 30 - Javascript

From the menu navigate through: view -> Command Palette Form the command palette search for Format Document and then select Prettier as your format engine.

I had prettier already working on another project, but for the new one I had do it through this way to enable it again for the new project.

Solution 31 - Javascript

in my case it was being hijacked by typescript formatter.

it was driving me crazy because it kept re-formatting my spaces!

to fix i did cmd+. (settings) type -> "default formatter"

and unchecked typescript

enter image description here

Solution 32 - Javascript

Don't forget to enable "editor.defaultFormatter" in the settings of the VSCode. In my case it was null and hence even the "editor.formatOnSave" was also not seeming to solve the issue.

Solution 33 - Javascript

I tried to enable "Format On Save" and set the "Auto Save Delay" to 0. It worked, so I guess you could try this too.

Edit: You can see them through these steps.

> 1. Manage(The gear Icon bottom left)

> 2. Settings(Inside the manage dropdown list)

> 3. Search for Format On Save and enable it(check the box)

> 4. Scroll down and look for Auto Save Delay and set it to 0

Solution 34 - Javascript

There are a few syntaxes that prettier is not able to parse. ?? is one of them. After removing the symbol my prettier worked like a charm. You should take a look at the output of the Prettier extension in vscode. That should point out the line and the syntax which is causing problems for prettier to format properly.

Solution 35 - Javascript

If you have set all things which you can do in Setting and Prettier is not working. Try to install it through this command line. npm install --save-dev prettier

Solution 36 - Javascript

here my prettier config working on vue.js files, typescript files and json files.

arrowParens: 'always'
bracketSpacing: true
endOfLine: 'crlf'
htmlWhitespaceSensitivity: 'css'
insertPragma: false
jsxBracketSameLine: false
jsxSingleQuote: true
overrides:
- files: '*.json'
  options:
    semi: true
    parser: 'json'
parser: 'babel'
printWidth: 120
proseWrap: 'preserve'
quoteProps: 'truepreserve'
requirePragma: false
semi: false
singleQuote: true
tabWidth: 8
trailingComma: 'es5'
useTabs: true
vueIndentScriptAndStyle: 

Do not forget to update your vscode settings

{
"extensions.ignoreRecommendations": false,
"editor.suggestSelection": "first",
"vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
"[json]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[vue]": {
    "editor.defaultFormatter": "octref.vetur"
},
"[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[html]": {
    "editor.defaultFormatter": "vscode.html-language-features"
},
"vetur.format.options.useTabs": true}

that's all folk's !

Solution 37 - Javascript

For my case i was using a windows machine and it turned out the file system had been corrupted thus prettier raised an error because it could not be able to open the config file due to file system corruption.

TO resolve it I run chkdsk /f h: on the terminal where h is the file partition.

This resolved the file corruption and prettier is now working fine.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBillal BegueradjView Question on Stackoverflow
Solution 1 - JavascriptMihaView Answer on Stackoverflow
Solution 2 - JavascriptlbragileView Answer on Stackoverflow
Solution 3 - JavascriptFacePalmView Answer on Stackoverflow
Solution 4 - JavascriptSimin MalekiView Answer on Stackoverflow
Solution 5 - JavascriptYmin HuView Answer on Stackoverflow
Solution 6 - JavascriptLevent DiviliogluView Answer on Stackoverflow
Solution 7 - JavascriptJuan CastanoView Answer on Stackoverflow
Solution 8 - JavascriptAlongkornView Answer on Stackoverflow
Solution 9 - JavascriptArsham AryaView Answer on Stackoverflow
Solution 10 - JavascriptsupiView Answer on Stackoverflow
Solution 11 - JavascriptLucasView Answer on Stackoverflow
Solution 12 - JavascriptManohar Reddy PoreddyView Answer on Stackoverflow
Solution 13 - JavascriptSkocdopoleView Answer on Stackoverflow
Solution 14 - JavascriptDeveshView Answer on Stackoverflow
Solution 15 - JavascriptZenoxView Answer on Stackoverflow
Solution 16 - JavascriptSrishtiView Answer on Stackoverflow
Solution 17 - JavascriptKendraView Answer on Stackoverflow
Solution 18 - JavascriptPankaj SharmaView Answer on Stackoverflow
Solution 19 - JavascriptWide AwakeView Answer on Stackoverflow
Solution 20 - JavascriptjaopView Answer on Stackoverflow
Solution 21 - Javascriptkartick shawView Answer on Stackoverflow
Solution 22 - JavascriptpiousonView Answer on Stackoverflow
Solution 23 - JavascriptTrueWillView Answer on Stackoverflow
Solution 24 - JavascriptSemjon MössingerView Answer on Stackoverflow
Solution 25 - JavascriptAli MonapourView Answer on Stackoverflow
Solution 26 - JavascriptRandall FlaggView Answer on Stackoverflow
Solution 27 - Javascriptgandharv gargView Answer on Stackoverflow
Solution 28 - JavascriptHayyaunView Answer on Stackoverflow
Solution 29 - JavascriptkissuView Answer on Stackoverflow
Solution 30 - JavascriptYaser AZView Answer on Stackoverflow
Solution 31 - JavascriptSonic SoulView Answer on Stackoverflow
Solution 32 - JavascriptSakthiView Answer on Stackoverflow
Solution 33 - JavascriptGarkView Answer on Stackoverflow
Solution 34 - JavascriptDevoreinView Answer on Stackoverflow
Solution 35 - JavascriptHuu Phong NguyenView Answer on Stackoverflow
Solution 36 - JavascriptmarcdahanView Answer on Stackoverflow
Solution 37 - JavascriptazwView Answer on Stackoverflow