Andath
Andath

Reputation: 22714

Why does Prettier not format code in VS Code?

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?

Upvotes: 643

Views: 888411

Answers (30)

A.Rahman Al-Khateeb
A.Rahman Al-Khateeb

Reputation: 83

Consider reading Prettier's log output from here

enter image description here

For me - and since the log output says that he couldn't find .prettierrc.json file - renaming .prettierrc file to .prettierrc.json solved that for me!

Upvotes: 1

Operator
Operator

Reputation: 582

In my case I simply just needed to check the Format On Save checkbox in the formatting settings. Press shift+cmd+p to bring up the search and then press Preferences: Open User Settings.

enter image description here

Edit, today on my new computer I had to also add this to settings.json

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

Upvotes: 6

Majid Shahmohammadi
Majid Shahmohammadi

Reputation: 377

To format your document, use Command + Shift + P and choose "Format Document with..."

enter image description here

Then, select "Configure Default Formatter..."

enter image description here

Finally, choose the desired option.

enter image description here

That's it!

Upvotes: 4

Miha
Miha

Reputation: 14938

  1. Select File -> Preferences -> Settings (Ctrl + comma) and search form formatter
  2. Set Prettiers as Default formatter. enter image description here

If above does not work:

ctrl+shift+p > Format Document With... > Configure Default Formatter... > Prettier - Code formatter

This also work with ctrl+shift+I

Upvotes: 1364

Mehrshad Farzaneh
Mehrshad Farzaneh

Reputation: 694

Simply Right click anywhere in the area where code formatting isn't working as expected

and Select Format Document With... from the context menu.

enter image description here

and then click on Configure Defulte Formatter...

enter image description here

and then click on Prettier in this list. enter image description here

This should resolve the issue after doing some changes on file and save that.

Upvotes: 14

Hafiz Muhammad Bilal
Hafiz Muhammad Bilal

Reputation: 315

I've tried done all stuff but my codebase is not getting formatted. Then I checked my .prettierignore & some other developer just wrote /src there.

I removed it & everything is working fine now

Upvotes: 0

Liam Pillay
Liam Pillay

Reputation: 806

Default formatter with modified elsewhere tag

For those looking to get this working with Prisma and other overriding extensions or project settings (like in the image above), use the following:

// Inside .vscode/settings.json
{
  // other extensions
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "[prisma]": { // replace this with the language that is overriding 
    "editor.defaultFormatter": "Prisma.prisma" // Replace this with the extension/formatter you want for that language
  },
  // rest of .vscode/settings.json
}

You shouldn't override project settings by forcing your editor settings as some other answers would suggest. This will just annoy your team and or whoever manages the repository you're working on.

Upvotes: 2

Matt Klein
Matt Klein

Reputation: 8424

Just in case, since its not already here...

I was trying to format a minified .js file in my node_modules folder so I could understand the code better and Prettier kept returning:

["INFO" - 7:13:19 PM] File is ignored, skipping.

In this case, you can force-format by opening the Command Palette Ctrl+Shift+P and then selecting Format Document (Forced) to have it format a file that would normally be ignored.

Forced

Upvotes: 0

FacePalm
FacePalm

Reputation: 11728

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.

A screenshot of the bottom right corner of the VS Code window, capturing the status bar in this region. One option is "Prettier," which has an X next to it indicating that errors are present.

Upvotes: 159

Levent Divilioglu
Levent Divilioglu

Reputation: 11602

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 - Format On Save

  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

Upvotes: 82

Greg
Greg

Reputation: 197

In the unlikely event that none of the above solutions work for you (like me), I had to set the default formatter to null in settings, then hit CTRL + SHIFT + P and search for "format document" (the default format document binding +R didn't work for me) then I was prompted to select a default formatter in a popup and after selecting prettier it formatted the document and also formats on saving now

Upvotes: 0

Werthis
Werthis

Reputation: 1117

I have same problem when I moved from Ubuntu to Windows 10.

The problem was with shortcuts 'ctrl + shirt + i', which was default on Ubuntu but was not in Win10.

Go to file -> preferences -> keyboard shortcuts.

Then write prettier and find 'Format Document (Forced)'. Click on pencil on left and write keyboard shortcut, press Enter.

If it is not possible because there is already command written to that shortcut, find it and change it to something else. Then it will be possible.

enter image description here

Upvotes: 1

Mohammad Reza Karimi
Mohammad Reza Karimi

Reputation: 2057

These three steps may solve your problem:

Prettier Doesn't format code

1 - Go to settings, then search for auto format

2 - Select Text Editor

3 - Select esbenp.prettier-vscode as your Default Formatter.

Simply said, go to Settings > User tab > Text Editor > Editor: Default Formatter and change it to prettier.

Upvotes: 32

Alejandro CM
Alejandro CM

Reputation: 137

I tried every single solution in this thread, and I just realized that my only issue was my Visual Studio color theme. That simple!

Before: enter image description here

After: enter image description here

Upvotes: -4

Dave O'Brien
Dave O'Brien

Reputation: 199

Check your package.json file for a property of prettier as this will take precedence.

{
  "name": "example",
  "scripts": { ... },

  "prettier": {},

  "dependencies": { ... },
  "devDependencies": { ... },
}

Delete this property and the .prettierrc file will be used.

The order of precedence is stated in the prettier docs.

Upvotes: 4

Zenox
Zenox

Reputation: 71

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

Print

Upvotes: 7

lbragile
lbragile

Reputation: 8122

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 Prettier - Code formatter (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

Upvotes: 559

Shivansh Upadyay
Shivansh Upadyay

Reputation: 31

For me it worked when I got rid of parser: json in the .pretterrc file.

Upvotes: 0

Andre Lopes
Andre Lopes

Reputation: 113

I am working in WSL (will also work for people having the problem only in cutom workspaces) and I tried EVERY fix possible until I found this tab on vscode settings: Image

Select the tab regarding your problem and change all the settings you want again and change the setting "Files: Auto Save" to either "onFocusChange" or "onWindowChange".

Upvotes: 3

Shahbaz A.
Shahbaz A.

Reputation: 4356

The only thing I needed to do was update my packages with a simple

npm install

I tried everything on here and it was still not working. Just seemed like it does not exist. Prettier was also added as a dependency in the project. It turned out that someone else had added or updated any package which caused my prettier to stop working.

Hoping it saves someone the headache it caused me.

Upvotes: 3

Eutrepe
Eutrepe

Reputation: 974

For me helped disabled this option in VS Code settings (then prettier use default config):

Prettier: Require Config

Upvotes: 2

Sonic Soul
Sonic Soul

Reputation: 24899

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

Upvotes: 13

Semjon Mössinger
Semjon Mössinger

Reputation: 1890

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

Upvotes: 6

Yaser AZ
Yaser AZ

Reputation: 518

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.

Upvotes: 4

Manohar Reddy Poreddy
Manohar Reddy Poreddy

Reputation: 27395

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:

Upvotes: 20

azw
azw

Reputation: 29

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.

Upvotes: 1

marcdahan
marcdahan

Reputation: 3042

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 !

Upvotes: 1

kissu
kissu

Reputation: 46596

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

Upvotes: 13

Hữu Phong
Hữu Phong

Reputation: 1603

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

Upvotes: 1

Kendra
Kendra

Reputation: 171

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.

Upvotes: 9

Related Questions