Почему не работает prettier vs code

Почему Prettier не форматирует код в VSCODE?

В моем приложении Nuxt, где установлены и включены ESlint и Prettier,я переключился на редактор кода Visual Studio.

Когда я открываю файл .vue, нажимаю CMD + Shift + P и выбираю формат документа, мой файл вообще не форматируется.

Мой .prettierrc параметры:

У меня так много строк исходного кода, что я не могу отформатировать их вручную. Что я делаю не так?

Ответы — Почему Prettier не форматирует код в VSCODE? / Why Prettier does not format code in VSCODE?

Это не проблема с самим Prettier, а prettier-vscode , расширением VSCode. Согласно его документации, форматирование Vue по умолчанию отключено:

красивее.disableLanguages (по умолчанию: [«Вью»])

Список идентификаторов языков, на которых можно отключить это расширение. Требуется перезагрузка. Примечание: отключение языка, включенного в родительской папке, предотвратит форматирование вместо запуска любого другого средства форматирования

Читайте также:  Если не работает роутер триколор

В этом случае для включения необходимо установить «prettier.disableLanguages»: [] . И поскольку это конфигурация расширения, вы должны сделать это в файле настроек VSCode, а не .prettierrc .

Иногда prettier перестает работать, когда в коде появляются синтаксические ошибки. Вы можете просмотреть ошибки, нажав на кнопку x в правом нижнем углу рядом с Prettier

можете ли вы попробовать добавить этот раздел в файл настроек пользователя?

Иногда при автоматическом обновлении плагинов необходимые файлы, используемые Prettier, могут пропасть .

Проверьте этот путь, если здесь присутствуют файлы или папка пуста

Если отсутствует деинсталляция и переустановка красивее

1. Используйте другое расширение красивее не работало для меня я просто использую другое расширение VSCODE с именем PrettierNow я думаю, что это поможет, сделано для меня.

2 .из последних обновлений prettier вам нужно добавить файл .prettierrc в корневой каталог проектов, если вы хотите придерживаться prettier. Пример .prettierrc таков-

Красивее может также формат файлов при сохранении.

Однако установка и включение не приводит к работе.

Вы должны проверить «формат сохранить» в VSCode: настройки >> пользователь >> текстовый редактор >> форматирование

Как я разобрался с этим после того, как испытал супер огромные разочарования из-за того, что Prettier перестал работать в VSCode.

  1. Выберите VS Code — > View ->> Command Palette и введите: > >Format Document With
  2. Затем Configure Default Formatter. , а затем выберите Prettier — Code formatter .

Это волшебным образом решило для меня проблему.

В зависимости от вашего случая это может вам помочь.

Я откатился назад красивее к 1.7.3 и исправил это

Включение функции «формат при сохранении» в VSCode: настройка > > > пользователь > > > > > > текстовый редактор >>>>>>>>>>> форматирование>>> > > > работало на меня!

Я не использую Vue, но у меня была та же проблема.

У меня уже были настройки

  • Editor: default formatter чтобы красивее
  • Editor: Format on Save — true
  • У меня уже были файлы .eslintrc.js и .prettierrc Но ничего не помогало.

Решение моей проблемы состояло в том, что я все установил правильно, за исключением того, что мне нужно было:

  • Command + Shift + p
  • тип format document with
  • выберите Configure Default Formatter.
  • по умолчанию выберите Editor: Format on Save 0.

Я не знаю, почему Editor: Format on Save , установленного на true , было недостаточно. Мне нужно было выбрать форматер по умолчанию, используя описанные выше шаги, чтобы он работал.

Для меня — это было связано с ESlint, который также работает с Prettier. Eslint не работал (конфликт локальной установки и глобальной установки), который сломался красивее.

Если выполнение того, о чем упоминал @Simin Maleki, не решит эту проблему для вас, есть вероятность, что ваш форматер по умолчанию не установлен:

Убедитесь, что ваше поле Editor: Default Formatter не null , а esbenp.prettier-vscode и что все языки ниже отмечены галочками. Это исправило мою проблему.

Не забудьте включить «editor. defaultFormatter» в настройках VSCode. В моем случае он был нулевым, и, следовательно, даже «editor.formatOnSave» также, казалось, не решал эту проблему.

Я столкнулся с этой проблемой и эти три шага решили мою проблему:

Если ни один из других ответов не работает, проверьте, что конфликтующая более красивая конфигурация .prettierrc не существует в вашем рабочем каталоге, или проверьте .prettierignore , чтобы убедиться, что файлы/папки не игнорируются.

  • Если вышесказанного нет, добавьте его вместо изменения.
  • Вы уже должны были установить «Prettier — code formatter», чтобы увидеть эффект от вышеуказанного изменения.

Недавно я столкнулся с той же проблемой, что Prettier не форматирует код автоматически при сохранении. Проверив красивее, я увидел ошибку: недопустимое значение «arrowParens» . Ожидалось «всегда» или «избегать», но получил true .

Сообщение об ошибке было замечено, когда я нажал на эту кнопку:

Оказалось,что у меня теперь и покрасивее установлено. Это имеет логическое значение в моем конфигурационном файле. После удаления Prettier Now все работает нормально.

Перейдите в раздел Управление(расположен в левом нижнем углу) — > > Настройки — > > вкладка пользователи -> > текстовый редактор — > > форматирование -> > проверьте формат при сохранении

если не работает, то закройте и снова откройте редактор vscode

Источник

Prettier Extension Not working in VS Code #1156

Comments

Nairitya commented Dec 20, 2019 •

Running the contributed command: ‘prettier.openOutput’ failed.
I am getting this error on VS code.

The text was updated successfully, but these errors were encountered:

Nairitya commented Dec 20, 2019

Prettier latest version [3.17.0]
vs code latest version 1.41.1
Format on Save is ‘ON’
Default Formatter esbenp.prettier-vscode

im-sven commented Dec 20, 2019

In my case this issue was caused by using the optional chaining operator (?). Try to run the prettier from the command line and see wether it returns any syntax errors.

williampsena commented Dec 20, 2019

I was facing the same problem.
But after reinstall, everything works again.

cpachmayr commented Dec 20, 2019

Having the same problem even after reinstalling. @williampsena did you mean resintalling the prettier extension, or reinstall VSCode?

williampsena commented Dec 20, 2019

Having the same problem even after reinstalling. @williampsena did you mean resintalling the prettier extension, or reinstall VSCode?

I reinstalled prettier extensions.

Nairitya commented Dec 20, 2019

Having the same problem even after reinstalling. @williampsena did you mean reinstalling the prettier extension, or reinstall VSCode?

I tried uninstalling and reinstalling Prettier Extension but it didn’t work for me so I uninstalled VS Code completely and then installed it again. Now Prettier is working fine. Earlier I was also using Auto Rename tag so maybe it was causing problem I don’t know but after uninstalling VS code completely, the problem is gone.

aelders-ncino commented Dec 20, 2019 •

Reinstalling prettier extensions did not work for me. Setup info:

Nairitya commented Dec 20, 2019 •

Reinstalling prettier extensions did not work for me. Setup info:

Yes, same here! reinstalling prettier didn’t work for me. So I uninstalled VS Code completely and then reinstalled it and then I installed Prettier and it is working now. Try this.

dlopatin-v commented Dec 22, 2019

Reinstall VS Code is not good solution.

ShahoG commented Dec 22, 2019

I suggest this be opened again as I have the same problem

iKettles commented Dec 22, 2019

Looks like this is fixed with b57b238 — I’ve updated the extension and all seems to be fine now.

dlopatin-v commented Dec 23, 2019 •

Looks like this is fixed with b57b238 — I’ve updated the extension and all seems to be fine now.

andrewktdoan commented Jan 12, 2020

I went down the list of issues and solutions and tried most of the suggestions and still not working for me. It works fine for JS but didn’t work for HTML for me. When I launch it, the «INFO» shows that it is enabled for a wider range of languages the instantly cut the list shorter and excluded HTML.

I’ve uninstalled the extension, VS Code, restarted my computer and reinstalled them back and still the same issue. Any other suggestions gentlemen and gentleladies?

Below is the INFO message I got.

[«INFO» — 8:23:22 PM] Enabling prettier for languages
[
«css»,
«graphql»,
«html»,
«javascript»,
«javascriptreact»,
«json»,
«json5»,
«jsonc»,
«less»,
«markdown»,
«mdx»,
«mongo»,
«postcss»,
«scss»,
«typescript»,
«typescriptreact»,
«vue»,
«yaml»
]
[«INFO» — 8:23:22 PM] Enabling prettier for range supported languages
[
«graphql»,
«javascript»,
«javascriptreact»,
«json»,
«typescript»,
«typescriptreact»
]

saurav1423 commented Mar 10, 2020

Error formatting document.
[«ERROR» — 10:45:54 AM] Unexpected closing tag «p». It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags (13:53)

I don’t know why this error is coming. If anyone has faced same problem then please let me know the solution.

paulmaunders commented Mar 28, 2020 •

It’s not working for me either. I get the info messages saying «Enabling prettier for range supported languages», but I can’t get it to prettify my code.

CMD + SHIFT + P only gives me the option for «Prettier: Create configuration file». I don’t see any option to run it on the code.

I tried reinstalling VSC and the extension, but that didn’t help. I’m using Prettier 3.20.0

paulmaunders commented Mar 28, 2020

OK I realised I had to press CMD + SHIFT + P, then type ‘Format document’ to get it to run. I should have read the manual more closely!

skeemybbob commented Apr 14, 2020

@paulmaunders that worked once. this is odd. I didn’t have to manually do it on my desktop, but on my MBP it only reformats when I do it that way, or when I do the (recently learned) keystroke method of opt+shift+F. Weird.

skeemybbob commented Apr 14, 2020

FOUND IT. under settings — search for «formatted» — Default was set to NULL. I changed it to ‘esbenp-prettier-vscode’ and had to select manually Editor: Format on Save. Now it works as it should.

eliamartani commented May 4, 2020

Pretty similar to you guys, I’ve selected the option «Format Document With. » found out the default was other than Prettier. Clicked «Configure Default Formatter. » and then Prettier.
Just in case any of you face similar issue in future.

allanaes commented May 13, 2020

Prettier latest version [3.17.0]
vs code latest version 1.41.1
Format on Save is ‘ON’
Default Formatter esbenp.prettier-vscode

In case someone like me don’t know this setting exists, this solves the problem. My default Editor:Default Formatter is set to null and Editor:Format on Save is not ticked. Thank you.

Источник

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 —

These are the extensions installed and enabled —

Prettier version — 2.2.2

VS Code version (from About VS code section) :

Please let me know how to get this issue fixed. Please leave a comment if any more info is needed. Thanks.

16 Answers 16

Same for me. I managed to solve it as follow:

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

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 (Cntr+, 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.

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:

You could also change this line in your configs to enable VS code html language support instead.

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:

Short Answer:

  1. open Prettier from the button on right bottom corner
  2. scroll up to see error list.
  3. 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.

If the formatting fails, see if there are any errors in the Prettier console. If not, use the following settings:

Once the file has been formatted, put back the original settings:

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).

This is what worked for me.

In the settings.json, capitalize the h in [html] :

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:

For reference, here are all my settings concerning linting and formatting:

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.

Источник

Оцените статью