Wrong formatting on save on VSCode - visual-studio-code

VSCode started to format my code in the wrong way.
E.g. I set it to use single quotes but VSCode changes it to double quotes on save.
I’ve disabled all extensions which could format code except for Prettier, checked all Prettier settings for User and Workflow (they are the same for now), and set Prettier as a default formatter for all types of files which I am working with.
But still, a code is formatted in the wrong way.
What else do I need to check to find what exactly format my files on save? How to fix this problem?
settings.json:
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.formatOnPaste": true,
"prettier.arrowParens": "avoid",
"prettier.jsxSingleQuote": true
}

Related

Disable Prettier from formatting inline JS in HTML files in VS Code

I'm running Prettier through ESLint using the eslint-config-prettier and eslint-plugin-prettier packages. I also have Prettier as a dev dependency to use on non-JS files. I use these two extensions with VS Code to validate and format my code automatically on save: Prettier - Code formatter and ESLint.
I'm having a problem with inline JS in HTML files. It appears as though the Prettier run through ESLint is either not being run, or is being overruled by the regular Prettier extension, even though in my config file I've explicitly set the option html.format.contentUnformatted to "pre,code,textarea,script" to prevent formatting that content with the default formatter. I'd like it to ignore content within script tags since ESLint should be handling the formatting there.
The relevant settings in my settings.json:
{
"javascript.validate.enable": false, // turns off default VS Code validation, I'm using ESLint's
"javascript.format.enable": false, // ^ see above
"editor.formatOnSave": true, // Turn on formatting for all files except JS/JSX
"[javascript]": {
"editor.formatOnSave": false
},
"[javascriptreact]": {
"editor.formatOnSave": false
},
"eslint.alwaysShowStatus": true,
"editor.codeActionsOnSave": {
"source.fixAll": true // Let ESLint fix all fixable errors on save
},
"eslint.run": "onSave", // Run ESLint on save
// Turn off Prettier for JS since we are doing it through Eslint already
"prettier.disableLanguages": ["javascript", "javascriptreact"],
"html.validate.scripts": false, // turn off default VSCode JS validation in HTML files
"editor.defaultFormatter": "esbenp.prettier-vscode", // Use Prettier formatter
"html.format.contentUnformatted": "pre,code,textarea,script" // Don't format content within these tags
}
Any idea what's wrong? I'm also open to suggestions of other ways to structure things. Thanks for any help!
You can use Prettier's embeddedLanguageFormatting option to achieve what you want. See https://prettier.io/docs/en/options.html#embedded-language-formatting
As for html.format.* VS Code settings, they're settings of the built-in formatter of VS Code and have nothing to do with Prettier.

Prettier in VS Code keeps breaking the line

So, I'm using VS Code with an extension called Prettier. The problem is that after I hit save my code is being "refined" but also separated into 2 lines even despite the fact it's a very short line and I still have plenty of space on the right. Could you please advice what setting is responsible for this conversion? It seems to me that I have checked all available options but unfortunately couldn't find anything which causes it.
"prettier.printWidth": "80"
in your settings.json or search for print width setting in the UI
Increase or decrease this setting. This limits the number of characters prettier limits a line to, it it exceeds this, it will try to break it into smaller ones.
Search for settings.json in visual studio.
You will find a json file in this path AppData\Roaming\Code\User\settings.json if it is a windows machine.
Add the below JSON in the file, If you keep "editor.formatOnSave" as false formatting won't happen when you save the file.
If you want to have this setting just make a specific property as false just the way I did for javascript and HTML in the below section.
"editor.formatOnSave": false,
"[handlebars]": {
"editor.formatOnSave": true
},
"[javascript]": {
"editor.formatOnSave": false
},
"[html]": {
"editor.formatOnSave": false
},
"[less]": {
"editor.formatOnSave": true
},

Prettier extension not formatting code on file save

I have installed prettier extension for VS Code, set it as default formatter, also set format on save to true in VS Code's settings file, and files are set to be saved automatically after some time delay.
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"files.autoSave": "afterDelay"
But prettier is not formatting my code when file is saved automatically after 2 seconds delay. Code is only formatted if i:
manually format the code using option + Shift + F keyboard shortcut.
press command + S
Here's my .prettierrc file
{
"trailingComma": "es5",
"tabWidth": 4,
"semi": true,
"singleQuote": true
}
How can i make prettier format my code automatically on file save?
After some searching, i found out that the following setting
"editor.formatOnSave": true
only works if:
Code formatter is available.
The files are NOT set to be saved after a delay.
And the editor must not be shutting down.
I had set the prettier as the default formatter using the following setting:
"editor.defaultFormatter": "esbenp.prettier-vscode"
But I had set files to be saved automatically after a delay as specified in the following setting:
"files.autoSave": "afterDelay"
This setting was the cause of the problem in my case.
"files.autoSave" setting can have one of the following values:
"off": A dirty editor is never automatically saved.
"afterDelay": A dirty editor is automatically saved after the configured files.autoSaveDelay.
"onFocusChange": A dirty editor is automatically saved when the editor loses focus.
"onWindowChange": A dirty editor is automatically saved when the window loses focus.
Setting "files.autoSave" to any possible value other than "afterDelay" will fix the issue. I solved this issue by setting "files.autoSave" to "onFocusChange".

Prettier not formatting HTML files in VS Code

Prettier extension on my VS code is unable to format HTML.
On load of VS code I am getting this error in my console -
On trying to format, I see this message in the bottom -
Note - TS files and SCSS files are being formatted properly. It is breaking only for HTML files.
Below is my HTML language based settings -
{
"tslint.rulesDirectory": "./node_modules/codelyzer",
"typescript.tsdk": "node_modules/typescript/lib",
"window.zoomLevel": 0,
"editor.formatOnSave": true,
"prettier.singleQuote": true,
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"files.associations": {
"*.html": "html"
}
}
These are the extensions installed and enabled -
Prettier version - 2.2.2
VS Code version (from About VS code section) :
Version: 1.38.1
Commit: b37e54c98e1a74ba89e03073e5a3761284e3ffb0
Date: 2019-09-11T13:31:32.854Z
Electron: 4.2.10
Chrome: 69.0.3497.128
Node.js: 10.11.0
V8: 6.9.427.31-electron.0
OS: Darwin x64 17.7.0
Please let me know how to get this issue fixed. Please leave a comment if any more info is needed. Thanks.
Same for me. I managed to solve it as follow:
{
"editor.formatOnSave": true,
"editor.formatOnPaste": true,
"editor.formatOnType": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features"
}
}
This allowed me to use prettier globally and use built in html formatter for html.
Also allowed the formatting to happen on save and while typing.
The part responsible for Prettier formatting html
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features"
},
I got the same issue, the cause can be updating the VS Code.
fixed it by setting the Default Formatter of Text Editor
Go to Settings (Ctrl+, for windows), search for 'Default Formatter'
Set the formatter in dropdown (esbenp.prettier-vscode) for prettier. this can change if you are using any other formatter.
Short Answer:
open Prettier from the button on right bottom corner
scroll up to see error list.
fix the wrong semantic you wrote.
ex:
photo for error example
Long Answer:
Most of the times the reason why Prettier doesn't work is that you have a markup error.
ex: you haven't close the angle braces or you close the tag more that one time
to know the error and fix it : look at short answer.
Firstly, you may want to solve the compilation error you have in regards to Vue.js. You may need to grab some extensions for VS-code as detailed here.
I have heard that Prettier has some issues formatting HTML at times, and VS Code itself already has HTML formatting support. You can stop prettier from formatting HTML specifically using the following command:
"prettier.disableLanguages": ["html"]
You could also change this line in your configs to enable VS code html language support instead.
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features"
}
Hope that helps!
For me i found that prettier was refusing to format files, however there was no errors in the output window in vs code. usually this happens when the html is not valid: missing tags, or tags closed twice, or tags that are not closed.
To see the errors, i ran prettier from the command line, and for each file it refused to format, it showed an error of what was wrong, like in the image below:
Had this problem crop up today after working fine with HTML previously.
Tried editing default formatter, format on save, reloading prettier etc.
Eventually tried the solution proposed above
edit settings.json
make sure "[html]": has default formatter line set to the below, found it on line 40.
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features"
},
Disabling "editor.formatOnSaveMode": "modifications" fixed the issue for me in Angular's .component.html files.
I had a lot of problems with getting Prettier to format on save. It turned out to be an issue with the default timeout settings in VSCode. Using these settings finally worked for me:
{
...
"editor.codeActionsOnSaveTimeout": 100000,
"editor.formatOnSaveTimeout": 100000,
...
}
For reference, here are all my settings concerning linting and formatting:
{
"editor.codeActionsOnSave": { "source.fixAll": true },
"editor.codeActionsOnSaveTimeout": 100000,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnPaste": true,
"editor.formatOnSave": true,
"editor.formatOnSaveTimeout": 100000,
"editor.formatOnType": true,
"eslint.alwaysShowStatus": true,
"eslint.enable": true,
"html.format.enable": false,
"htmlhint.enable": true,
"prettier.requireConfig": false,
"prettier.useEditorConfig": true,
"stylelint.autoFixOnSave": true,
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
}
}
I use the following extensions (again limited to linting/formatting):
ESLint (dbaeumer.vscode-eslint)
Prettier (esbenp.prettier-vscode)
stylelint-plus (hex-ci.stylelint-plus)
HTMLHint (mkaufman.htmlhint)
You might want to make sure that all the npm packages needed by your extensions are installed. Locally if possible.
I sincerely hope this helps. Setting up linters and formatters is still a science in its own right.
P.S. I get an error like your 'cannot format' message whenever I try to format a file that is not inside the working directory. But looking at the path in your message suggests that this is not an issue in your case.
If the formatting fails, see if there are any errors in the Prettier console.
If not, use the following settings:
"[html]": {
// "editor.defaultFormatter": "esbenp.prettier-vscode"
"editor.defaultFormatter": "vscode.html-language-features"
},
Once the file has been formatted, put back the original settings:
"[html]": {
// "editor.defaultFormatter": "esbenp.prettier-vscode"
"editor.defaultFormatter": "vscode.html-language-features"
},
And try formatting again. This time Prettier will have better input to work with.
The requirePragma option should be false (it is by default) in .prettierrc or VS code prettier settings (dotfile overrides VS).
I simply solved it by right-clicking in the file, select 'Format Document with' and choose 'prettier'. I don't know how to permanently set it up but it's a quick workaround.
This is what worked for me.
In the settings.json, capitalize the h in [html]:
...
"[Html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
...
prettier formatter doesn't support Format on selection or Formate On Save for HTML files - modification mode, So for this, you can set formatOnSaveMode:'html' for HTML files in settings.json
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSaveMode": "file"
},
Format selection works on several languages depending on what Prettier itself supports. The following languages currently are supported:
javascript
javascriptreact
typescript
typescriptreact
json
graphql
I just changed the default formatter for HTML to VScode's HTML formatter.
Open the command palette with Ctrl + Shift + P (or use ⌘ + Shift + P for Mac).
To open the user settings.json file search for and select the Open User Settings (JSON) option.
Make the following changes.
// "[html]": {
// "editor.defaultFormatter": "esbenp.prettier-vscode"
// },
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features"
},
Adding this to the bottom of my VSCode User settings did the job for me:
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
I have found Prettier to be annoying sometimes with HTML. Hence in my case this worked for me for HTML formatting-
user json file settings as follows-
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[html]": {
"editor.defaultFormatter": "lonefy.vscode-JS-CSS-HTML-formatter"
},
For HTML I use JS-CSS-HTML Formatter extension in VSCode as the default formatter (as you can see in code above). This formats the HTML code well.
I had the same issue and fixed it by navigating to the settings (ctrl + shift + ,)
type in the search default format
then check HTML -> format: enable box
For me, I had to check the notifications in the bottom right corner. Once I clicked on it, you can configure which formatter to use. For some reason, there are more than one editor. I'm gonna go on a limp and assume that it's conflicting somehow with the editors global config file.
To open the command palette, you can use COMMAND + SHIFT + P on macOS or CTRL + SHIFT + P on Windows.
In the command palette, search for format and then choose Format Document.
You may then be prompted to choose which format to use. To do so, click the Configure button. Then choose Prettier - Code Formatter or another prettier code formatter.
Your code is now formatted with spacing, line wrapping, and consistent quotes.
Simple and easy way to make it work.
Steps:
Open VSCode, go to Settings (Ctrl+, for windows), search for Default Formatter
Set the formatter in dropdown (esbenp.prettier-vscode) for prettier. this can change if you are using any other formatter.
Extra step, if you want to use it on the save file. Just search for Format on save, then check that it is TRUE
Restart your VSCode, and Happy coding. 🤗👏
One of my peers installed the following into the workspace vscode:
"prettier.disableLanguages": ["html"],
That would do it.
Use This as your config
"prettier.singleQuote": true,
"prettier.useEditorConfig": false,
"prettier.useTabs": true,
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[css]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
"[Html]": {
//"editor.defaultFormatter": "vscode.html-language-features"
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
this work for me
Try restarting VS Code
I've had Prettier stop formatting things when VS Code prompted me to restart to update. Closing and opening VS Code got it working again.

How do you format code on save in VS Code

I would like to automatically format TypeScript code using the build-in formatter when I save a file in Visual Studio Code.
I'm aware of the following options, but none of them is good enough:
Format manually Shift + Alt + F
Format on type "editor.formatOnType": true
It formats the line when you press enter. Unfortunatelly, it leaves it unformatted when you mouse-click another line or press up/down arrow.
Use existing extension
I tried this one, but it does not seem to work too well.
Use beautify "beautify.onSave": true
It does not work with TypeScript
Write custom extension
It's tricky if you want to handle autosaves and builds correctly.
As of September 2016 (VSCode 1.6), this is now officially supported.
Add the following to your settings.json file:
"editor.formatOnSave": true
No need to add commands anymore. For those who are new to Visual Studio Code and searching for an easy way to format code on saving, kindly follow the below steps.
Open Settings by pressing [Cmd+,] in Mac (or [Ctrl+,] in Windows/Linux) or using the below screenshot.
Type 'format' in the search box and enable the option 'Format On Save'.
You are done. Thank you.
If you would like to auto format on save just with Javascript source, add this one into Users Setting (press CmdShiftP or CtrlShiftP then type Open Settings (JSON) to open settings.json file)
"[javascript]": { "editor.formatOnSave": true }
For eslint:
"editor.codeActionsOnSave": { "source.fixAll.eslint": true }
For neet formatting for any language you can use Prettier - code formatter.
After applying this you can format code Alt + Shift + f
The best to avoid conflicts is defining individual formatters for each language, for instance if I am working with Rust and Typescript I would like to format code using the extensions Rust-Analyzer and Prettier respectively, therefore on my .vscode/settings.json:
{
"editor.defaultFormatter": null,
"[rust]": {
"editor.defaultFormatter": "rust-lang.rust-analyzer",
"editor.formatOnSave": true
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
}
}
Remember that both Prettier and rust-analyzer extensions must be installed first.
For MAC user,
add this line into your Default Settings
File path is: /Users/USER_NAME/Library/Application Support/Code/User/settings.json
"tslint.autoFixOnSave": true
Sample of the file would be:
{
"window.zoomLevel": 0,
"workbench.iconTheme": "vscode-icons",
"typescript.check.tscVersion": false,
"vsicons.projectDetection.disableDetect": true,
"typescript.updateImportsOnFileMove.enabled": "always",
"eslint.autoFixOnSave": true,
"tslint.autoFixOnSave": true
}
After hours of struggle... below steps worked.
Full details below.
Install this extension
https://marketplace.visualstudio.com/items?itemName=pucelle.run-on-save
Add below json, to below file:
File:
<your-project-directory>\.vscode\settings.json
OR
%UserProfile%\AppData\Roaming\Code\User\settings.json
JSON:
NOTE: Make sure commas before and after below block.
"files.autoSave": "afterDelay",
"files.autoSaveDelay": 1000,
"runOnSave.statusMessageTimeout": 3000,
"runOnSave.commands": [
{
"match": ".*\\.*",
"command": "editor.action.formatDocument",
"runIn": "vscode"
}
],
Now, when the code is changed, after 1 second, it gets formatted & saved automatically.
For me formatOnSave wasn't working because I had prettier installed and hadn't yet chosen between the built-in and prettier as my default formatter.
To trigger the selection dialog I had to press Alt + Shift + f on my json file.
First, you need to choose the formatter which you have just added as an extension.
Press ctrl + alt + f and choose the formatter that you want from the dropdown.
Post that with every save it will get automatically formatted.
If you use Prettier and this line
"editor.formatOnSave": true
Doesn't work to format on save, you might need to add another command to settings.json
"editor.defaultFormatter": "esbenp.prettier-vscode",
In addition to enabling setting Format On Save, for python developers, you may need to install autopep8 package which is used by vscode as default to format the python code when the code is saved.
pip install autopep8
and then, press ctrl + s to see changes.
Goto settings and search format
check Editor: Format On Save
or follow these steps