Prettier error formatting document

Summary I have my editor configured to format on save. When I save a .js or .jsx file, I get the warning triangle indicator in the bottom right, and the message "Error formatting document&quot...

Summary

I have my editor configured to format on save. When I save a .js or .jsx file, I get the warning triangle indicator in the bottom right, and the message «Error formatting document» in the Prettier logs.

Github Repository to Reproduce Issue

https://github.com/DataBiosphere/jade-data-repo-ui

Steps To Reproduce:

  1. Edit a .js or .jsx file
  2. Save the file

Expected result

Prettier should have detected any issues and formatted the file correctly.

Actual result

Prettier throws an error:

["INFO" - 3:48:31 PM] Using ignore file (if present) at /Users/myessail/broad/jade-data-repo-ui/.prettierignore
["INFO" - 3:48:31 PM] Loaded module 'prettier@2.0.5' from '/Users/myessail/broad/jade-data-repo-ui/node_modules/prettier/index.js'
["INFO" - 3:48:31 PM] File Info:
{
  "ignored": false,
  "inferredParser": "babel"
}
["INFO" - 3:48:31 PM] Detected local configuration (i.e. .prettierrc or .editorconfig), VS Code configuration will not be used
["INFO" - 3:48:31 PM] Prettier Options:
{
  "filepath": "/Users/myessail/broad/jade-data-repo-ui/src/components/dataset/query/sidebar/filter/FreetextFilter.jsx",
  "parser": "babel",
  "useTabs": false,
  "tabWidth": 2,
  "endOfLine": "lf",
  "printWidth": 100,
  "singleQuote": true,
  "trailingComma": "all",
  "jsxBracketSameLine": false
}
["ERROR" - 3:48:31 PM] Error formatting document.
["INFO" - 3:48:31 PM] Formatting completed in 12.922509ms.

Additional information

I’ve experienced this problem once before, and the only way I was able to resolve it was to uninstall and reinstall VSCode, which is not an acceptable solution. If I run Prettier from the command line, it works with no issues.

My settings.json:

{
  "workbench.colorTheme": "Noctis Lux",
  "editor.formatOnSave": true,
  "[javascriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "editor.suggestSelection": "first",
  "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
  "editor.formatOnPaste": true,
  "files.autoSave": "off",
  "window.zoomLevel": 0,
  "prettier.eslintIntegration": true,
  "[jsonc]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "editor.codeActionsOnSave": {
    // For ESLint
    "source.fixAll.eslint": true
  }
}

VS Code Version:

Version: 1.46.1
Commit: cd9ea6488829f560dc949a8b2fb789f3cdc05f5d
Date: 2020-06-17T21:17:14.222Z
Electron: 7.3.1
Chrome: 78.0.3904.130
Node.js: 12.8.1
V8: 7.8.279.23-electron.0
OS: Darwin x64 18.7.0

Prettier Extension Version:

5.1.0

OS and version:

Mac OS Mojave 10.14.6 (18G3020)

Prettier Log Output

["INFO" - 3:48:31 PM] Formatting /Users/myessail/broad/jade-data-repo-ui/src/components/dataset/query/sidebar/filter/FreetextFilter.jsx
["INFO" - 3:48:31 PM] Using ignore file (if present) at /Users/myessail/broad/jade-data-repo-ui/.prettierignore
["INFO" - 3:48:31 PM] Loaded module 'prettier@2.0.5' from '/Users/myessail/broad/jade-data-repo-ui/node_modules/prettier/index.js'
["INFO" - 3:48:31 PM] File Info:
{
  "ignored": false,
  "inferredParser": "babel"
}
["INFO" - 3:48:31 PM] Detected local configuration (i.e. .prettierrc or .editorconfig), VS Code configuration will not be used
["INFO" - 3:48:31 PM] Prettier Options:
{
  "filepath": "/Users/myessail/broad/jade-data-repo-ui/src/components/dataset/query/sidebar/filter/FreetextFilter.jsx",
  "parser": "babel",
  "useTabs": false,
  "tabWidth": 2,
  "endOfLine": "lf",
  "printWidth": 100,
  "singleQuote": true,
  "trailingComma": "all",
  "jsxBracketSameLine": false
}
["ERROR" - 3:48:31 PM] Error formatting document.
["INFO" - 3:48:31 PM] Formatting completed in 12.922509ms.

Статья написана студентом Хекслета. Мнение автора может не совпадать с позицией редакции

Руководство для настройки автоматического форматирования кода и проверки синтаксиса языка JavaScript. Рассказываем про утилиты Eslint и Prettier.

  • Введение
    • Какие проблемы решает eslint?
    • Для чего тогда нам нужен Prettier?
    • Перейдем к настройке
    • Для автоматического форматирования нам нужно
  • Заключение

Введение

В этой статье мы рассмотрим основные правила линтера и способы его настройки под проект.

Какой цели я хочу достигнуть в результате?

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

Какие проблемы решает eslint?

Линтер — это статический анализатор для языка программирования. Он сообщает о потенциально опасных выражениях в коде, которые могут привести к аварийному завершению программы. Также линтер может сообщить об устаревших участках кода, синтаксических ошибках и неиспользованных переменных. Всего существует около 300 правил, которые можно включить/выключить по желанию.

Для чего тогда нам нужен Prettier?

На большом проекте, как правило, работает несколько программистов. У каждого из них может быть свое мнение относительно качества кода и размера отступов в строке. Eslint может форматировать текст, но требует дополнительной кропотливой настройки. Облегчить задачу призвана утилита Prettier. У нее открытый исходный код и имеется хорошая поддержка сообщества. Большая часть правил оформления уже задана по умолчанию, но у пакета есть гибкая система настройки и удобный API, позволяющий описывать свои правила в конфигурационном файле формата .json/.yml. Это значит, что мы можем написать файл с едиными настройками для всей команды.

Никогда не останавливайтесь:
В программировании говорят, что нужно постоянно учиться даже для того, чтобы просто находиться на месте. Развивайтесь с нами — на Хекслете есть сотни курсов по разработке на разных языках и технологиях.

Перейдем к настройке

Начну с того, что здесь описана настройка линтера на примере VScode. Для других IDE будет разница только в поиске нужных расширений. Итак:

  1. Откройте Vscode и найдите в левой боковой панели пункт Extensions (ctrl/cmd+shift+X)
  2. В строке поиска введите ESLint и установите пакет от Dirk Baeumer.
  3. Проделайте аналогичную операцию для Prettier — Code formatter. (может потребоваться перезагрузка редактора после установки).
  4. Дальше нам нужно установить сам линтер с помощью команды npm install eslint --save-dev
  5. После установки линтера мы можем воспользоваться стандартным скриптом для базовой настройки конфигурационного файла. Для этого пишем в консоли следующую команду: eslint --init
  6. Скрипт попросит ответить нас на вопросы о текущем проекте и выставит соответствующие правила:

Можете поэкспериментировать с настройками, чтобы понять, какой пункт меню за что отвечает. Итогом настройки будет являться сформированный файл .eslintrc.json. Вы можете создать файл с настройками самостоятельно и поместить его на один уровень с package.json.

Для того, чтобы наша проверка работала, нам нужно установить необходимые пакеты:

npm install --save-dev eslint eslint-plugin-prettier eslint-config-prettier babel-eslint
npm install --save-dev --save-exact prettier

Если вы создали файл конфигурации с помощью eslint —init, скрипт предложит вам автоматически установить пакет для работы с React. Если вы хотите сделать это самостоятельно — пропишите:

npm install eslint-plugin-react --save-dev

Пример настройки файлов для работы ESLint:

[0]=off // выключает правило

[1]=warn // выводит предупреждение в консоль

[2]=error // выводит error и останавливает исполнение программы

.eslintrc.json

{
    "env": { // где будет исполняться наш код
        "browser": true,
        "es2021": true 
    },
    /* Пресет с настройками. prettier должен быть последним. 
    Он удаляет некоторые правила eslint из-за которых могут возникать конфликты. */
    "extends": [ 
        "eslint:recommended",
        "plugin:react/recommended",
        "prettier"
    ],
    "parser": "babel-eslint", // Парсер для обработки jsx кода
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 11, // версия стандарта JavaScript. Последний 12 (2021).
        "sourceType": "module" // Позволяет использовать import/export
    },
    // Здесь мы подключаем используемые плагины.
    "plugins": [
        "react", 
        "prettier"
    ],
    /* Правила для отслеживания линтером. Если пресеты покрывают не все ситуации, 
    вы можете прописать нужные правила вручную. */)
    "rules": {
        "prettier/prettier": "error", . // Обязательно!! Подсвечивает ошибки из Prettier.
        "react/prop-types": 0 // Отключаем правило проверки передаваемых типов.
    }
}

.prettierrc.json

*Правила оформления кода. Полный список настроек вы можете найти здесь.

{
    "singleQuote": true,
    "jsxSingleQuote": true,
    "arrowParens": "always",
    "max-len": ["error", 140, 2],
    "tabWidth": 2,
    "useTabs": false
}

.eslintignore

Чтобы исключить из проверки директории/файлы указываем их в виде списка

test/fixtures
**/app/public
node_modules
/* название файла */

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

Для автоматического форматирования нам нужно

  • Зайти в настройки — Ctrl/Cmd +Shift + P
  • В строку поиска вписать — settings
  • Выбрать пункт — Preferences: Open Settings (JSON)
    В файле settings.json добавляем:
{
    "[javascript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode" // Prettier, как форматтер по умолчанию
    "editor.codeActionsOnSave": {
        "source.fixAll": true // работает аналогично eslint --fix
        },
    },
    "editor.formatOnSave": true
}

Tip. Если у вас возникли проблемы во время работы с ESLint, перейдите во вкладку Output и посмотрите вывод об ошибках.

TROUBLESHOOTING

  1. Q: Что делать, если при работе на Windows возникает следующая ошибка?
    [eslint] Delete 'cr' [prettier/prettier].
    A: Чтобы её решить, нужно немного поменять настройки в файле .eslintrc.json

    "prettier/prettier": ["error", {
    "endOfLine":"auto"
    }],
  2. Q: Не работают правила линтера или форматирование отличается от ожидаемого.
    A: Возможно, это следствие наличия в проекте других конфигурационных файлов. Они имеют разный приоритет исполнения. Например, файл .editorconfig имеет высший приоритет, чем .eslintrc., поэтому линтер будет выставлять настройки с его помощью.
  3. Q: Выставляются двойные скобки, вместо одинарных.
    A: Чаще всего это происходит из-за конфликта настроек линтера и prettier. Некоторые пресеты (extends в файле .eslintrc.json) содержат в себе правила настройки форматирования скобок. Последний указанный пресет переписывает правила предыдущих. Убедитесь в том, что "prettier" находится последним в списке extends.

Заключение

Часто в проектах могут использовать популярный конфиг от Airbnb. Он содержит больше правил и может вас запутать, поэтому рекомендую к нему обращаться после того, как усвоите базовые принципы работы линтера. Спасибо, что дочитали до конца. Работать с кодом теперь будет более приятно и гораздо быстрее.

Прокачивайте свой уровень программирования:
На Хекслете есть несколько десятков треков — специальных курсов для опытных программистов, позволяющие повысить уровень компетентности разработчика в разных направлениях.

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.


JavaScript
· TypeScript
· Flow
· JSX
· JSON



CSS
· SCSS
· Less



HTML
· Vue
· Angular


HANDLEBARS
· Ember
· Glimmer



GraphQL
· Markdown
· YAML


Your favorite language?

Build Status

VS Code Marketplace Downloads

VS Code Marketplace Installs

code style: prettier

Follow Prettier on Twitter

Installation

Install through VS Code extensions. Search for Prettier - Code formatter

Visual Studio Code Market Place: Prettier — Code formatter

Can also be installed in VS Code: Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.

ext install esbenp.prettier-vscode

Default Formatter

To ensure that this extension is used over other extensions you may have installed, be sure to set it as the default formatter in your VS Code settings. This setting can be set for all languages or by a specific language.

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

If you want to disable Prettier on a particular language you can either create a .prettierignore file or you can use VS Code’s editor.defaultFormatter settings.

The following will use Prettier for all languages except Javascript.

{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "[javascript]": {
    "editor.defaultFormatter": "<another formatter>"
  }
}

The following will use Prettier for only Javascript.

{
  "editor.defaultFormatter": "<another formatter>",
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

Additionally, you can disable format on save for specific languages if you don’t want them to be automatically formatted.

{
  "[javascript]": {
    "editor.formatOnSave": false
  }
}

Prettier Resolution

This extension will use prettier from your project’s local dependencies (recommended). When the prettier.resolveGlobalModules is set to true the extension can also attempt to resolve global modules. Should prettier not be installed locally with your project’s dependencies or globally on the machine, the version of prettier that is bundled with the extension will be used.

To install prettier in your project and pin its version as recommended, run:

npm install prettier -D --save-exact

NOTE: You will be prompted to confirm that you want the extension to load a Prettier module. This is done to ensure that you are not loading a module or script that is not trusted.

Plugins

This extension supports Prettier plugins when you are using a locally or globally resolved version of prettier. If you have Prettier and a plugin registered in your package.json, this extension will attempt to register the language and provide automatic code formatting for the built-in and plugin languages.

Configuration

There are multiple options for configuring Prettier with this extension. You can use VS Code settings, prettier configuration files, or an .editorconfig file. The VS Code settings are meant to be used as a fallback and are generally intended only for use on non-project files. It is recommended that you always include a prettier configuration file in your project specifying all settings for your project. This will ensure that no matter how you run prettier — from this extension, from the CLI, or from another IDE with Prettier, the same settings will get applied.

Using Prettier Configuration files to set formatting options is the recommended approach. Options are searched recursively down from the file being formatted so if you want to apply prettier settings to your entire project simply set a configuration in the root. Settings can also be configured through VS Code — however, these settings will only apply while running the extension, not when running prettier through the command line.

Configuring Default Options

Some users may not wish to create a new Prettier config for every project or use the VS Code settings. In order to set a default configuration, set prettier.configPath. However, be careful, if this is set this value will always be used and local configuration files will be ignored.

Visual Studio Code Settings

You can use VS Code settings to configure prettier. Settings will be read from (listed by priority):

  1. Prettier configuration file
  2. .editorconfig
  3. Visual Studio Code Settings (Ignored if any other configuration is present)

NOTE: If any local configuration file is present (i.e. .prettierrc) the VS Code settings will NOT be used.

Usage

Using Command Palette (CMD/CTRL + Shift + P)

1. CMD + Shift + P -> Format Document
OR
1. Select the text you want to Prettify
2. CMD + Shift + P -> Format Selection

Keyboard Shortcuts

Visual Studio Code provides default keyboard shortcuts for code formatting. You can learn about these for each platform in the VS Code documentation.

If you don’t like the defaults, you can rebind editor.action.formatDocument and editor.action.formatSelection in the keyboard shortcuts menu of vscode.

Format On Save

Respects editor.formatOnSave setting.

You can turn on format-on-save on a per-language basis by scoping the setting:

// Set the default
"editor.formatOnSave": false,
// Enable per-language
"[javascript]": {
    "editor.formatOnSave": true
}

Format Selection

Format selection works on several languages depending on what Prettier itself supports. The following languages currently are supported:

javascript
javascriptreact
typescript
typescriptreact
json
graphql
handlebars

Format Document (Forced)

If you would like to format a document that is configured to be ignored by Prettier either because it is in a .prettierignore file or part of a normally excluded location like node_modules, you can run the command Format Document (Forced) to force the document to be formatted. Forced mode will also ignore any config for requirePragma allowing you to format files without the pragma comment present.

Linter Integration

The recommended way of integrating with linters is to let Prettier do the formatting and configure the linter to not deal with formatting rules. You can find instructions on how to configure each linter on the Prettier docs site. You can then use each of the linting extensions as you normally would. For details refer to the Prettier documentation.

Workspace Trust

This extension utilizes VS Code Workspace Trust features. When this extension is run on an untrusted workspace, it will only use the built in version of prettier. No plugins, local, or global modules will be supported. Additionally, certain settings are also restricted — see each setting for details.

Settings

Prettier Settings

All prettier options can be configured directly in this extension. These settings are used as a fallback when no configuration file is present in your project, see the configuration section of this document for more details. For reference on the options see the prettier documentation.

The default values of these configurations are always to their Prettier 2.0 defaults. In order to use defaults from earlier versions of prettier you must set them manually using your VS Code settings or local project configurations.

prettier.arrowParens
prettier.bracketSpacing
prettier.endOfLine
prettier.htmlWhitespaceSensitivity
prettier.insertPragma
prettier.singleAttributePerLine
prettier.bracketSameLine
prettier.jsxBracketSameLine
prettier.jsxSingleQuote
prettier.printWidth
prettier.proseWrap
prettier.quoteProps
prettier.requirePragma
prettier.semi
prettier.singleQuote
prettier.tabWidth
prettier.trailingComma
prettier.useTabs
prettier.vueIndentScriptAndStyle
prettier.embeddedLanguageFormatting

Extension Settings

These settings are specific to VS Code and need to be set in the VS Code settings file. See the documentation for how to do that.

prettier.enable (default: true)

Controls whether prettier is enabled or not. You must restart VS Code when you change this setting.

prettier.requireConfig (default: false)

Require a prettier configuration file to format files. Untitled files will still be formatted using the VS Code Prettier configuration even with this option set to true.

prettier.ignorePath (default: .prettierignore)

Supply the path to an ignore file such as .gitignore or .prettierignore.
Files which match will not be formatted. Set to null to not read ignore files.

Note, if this is set, this value will always be used and local ignore files will be ignored.

Disabled on untrusted workspaces

prettier.configPath

Supply a custom path to the prettier configuration file.

Note, if this is set, this value will always be used and local configuration files will be ignored. A better option for global defaults is to put a ~/.prettierrc file in your home directory.

Disabled on untrusted workspaces

prettier.prettierPath

Supply a custom path to the prettier module. This path should be to the module folder, not the bin/script path. i.e. ./node_modules/prettier, not ./bin/prettier.

Disabled on untrusted workspaces

prettier.resolveGlobalModules (default: false)

When enabled, this extension will attempt to use global npm or yarn modules if local modules cannot be resolved.

NOTE: This setting can have a negative performance impact, particularly on Windows when you have attached network drives. Only enable this if you must use global modules. It is recommended that you always use local modules when possible.

Note: Disabling a language enabled in a parent folder will prevent formatting instead of letting any other formatter to run

Disabled on untrusted workspaces

prettier.documentSelectors

A list of glob patterns to register Prettier formatter. Typically these will be in the format of **/*.abc to tell this extension to register itself as the formatter for all files with the abc extension. This feature can be useful when you have overrides set in your config file to map custom extensions to a parser.

It is likely will need to also update your prettier config. For example, if I register the following document selector by itself, Prettier still won’t know what to do with that file. I either need a Prettier extension that formats .abc file format or I need to configure Prettier.

{
  "prettier.documentSelectors": ["**/*.abc"]
}

To tell Prettier how to format a file of type .abc I can set an override in the prettier config that makes this file type use the babel parser.

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

Disabled on untrusted workspaces

prettier.useEditorConfig (default: true)

Whether or not to take .editorconfig into account when parsing configuration. See the prettier.resolveConfig docs for details.

Disabled on untrusted workspaces (always false)

prettier.withNodeModules (default: false)

Whether or not to process files in the node_modules folder.

Disabled on untrusted workspaces

Error Messages

Failed to load module. If you have prettier or plugins referenced in package.json, ensure you have run npm install

When a package.json is present in your project and it contains prettier, plugins, or linter libraries this extension will attempt to load these modules from your node_module folder. If you see this error, it most likely means you need to run npm install or yarn install to install the packages in your package.json.

Your project is configured to use an outdated version of prettier that cannot be used by this extension. Upgrade to the latest version of prettier.

You must upgrade to a newer version of prettier.

This workspace is not trusted. Using the bundled version of prettier.

You must trust this workspace to use plugins and local/global modules. See: Workspace Trust

You can configure JavaScript code auto-formatting with Prettier to work per-project. This allows you to get a consistent formatting without thinking or arguing about it. This blog post shows how to configure Prettier to work from command line, from VSCode and from Git hooks.

You can find the sample project with different Prettier settings configured per-subfolder at bahmutov/prettier-config-example.

  • Why Prettier?
  • Setup
  • Settings
  • VSCode setup
  • Format files from CLI
  • Format staged files on commit
  • Catch mis-formatted files on CI
    • Using stop-build
    • Using Prettier
  • Common problems
    • Nothing happens on save
    • Code formatting is wrong
  • Tips
    • Print width
    • Ignoring files
    • Saving without formatting
    • Temporarily disable formatting
    • Only format configured projects
    • Ignore parts of files
  • Use Eslint with Prettier
    • Disable style rules in ESLint
    • ESLint and React
    • Integrate ESLint in VSCode
    • Run Prettier from ESLint
    • VSCode + ESLint + Prettier setup
    • VSCode + ESLint + Prettier + TypeScript setup
    • Use Prettier + ESLint + Cypress
    • Catch exclusive tests
  • Common ESLint problems
    • Disable a rule
    • Errors shown for async keyword
  • Other languages
    • Format other languages with Prettier
    • Format JSON files with Prettier
    • Use custom settings overrides
  • Chrome extension
  • Run Prettier inside GitHub Action

Why Prettier?

Prettier reformats your JavaScript code consistently and (arguably) in way that is easy to read and understand. It takes whatever copy/pasted code snippets you put into your file and makes it look the same as the rest of the code. By using Prettier your team skips ALL disagreements about spacing, variable declarations, semi-colons, trailing commas, etc. The code just magically gets to the format you pick.

You can use Prettier from command line, or from your code editor whenever you paste or save a file. I prefer to use two solutions described in this blog post:

  • format the file from VSCode every time I save it
  • format the changed files on Git commit before committing them

Let me show you how to do both.

Setup

When setting up Prettier it is important to configure it per-project. Not every project uses the same code style, thus it is important to respect the style of whatever project you are currently working in. The demo repo bahmutov/prettier-config-example has two subfolders, each with its distinct code style, enforced by Prettier. In reality, each of your repos will have its style; I am using subfolders in order to keep the example simple.

I assume you are using NPM and have package.json file inside the repository. Install Prettier

1
npm install --save-dev --save-exact prettier

At the root of the project create the Prettier configuration file. In my example I have two subfolders, and there is a configuration file in each subfolder:

1
2
3
4
5
prettier-config-example/
projectA/
.prettierrc.json
projectB/
.prettierrc.json

I like using JSON configuration format so my code editor helps me. In fact, VSCode understands the Prettier configuration file format via the built-in json schema. So when I edit projectA/.prettierrc.json file, I get intelligent tooltips.

Picking trailing comma setting

Settings

Prettier tries to enforce the same code style without 100s of options, thus there are just a few settings you can change. Here are settings I am using in the first project to make it look «traditional» ES5

projectA/.prettierrc.json
1
2
3
4
5
6
{
"trailingComma":"none",
"tabWidth": 4,
"semi": true,
"singleQuote": false
}

The second project uses more modern style without semi-colons and with trailing commas.

projectB/.prettierrc.json
1
2
3
4
5
6
{
"trailingComma": "all",
"tabWidth": 2,
"semi": false,
"singleQuote": true
}

VSCode setup

To use the Prettier we have just installed from VSCode we need to install the Prettier VSCode extension:

  1. Launch VS Code Quick Open (Ctrl+P)
  2. Run the following command
1
ext install esbenp.prettier-vscode

Because you might have global settings related to code formatting, I prefer having in each repository a file with local workspace VSCode settings. I commit this file .vscode/settings.json to source control to make sure everyone uses the same extension to format the code.

.vscode/settings.json
1
2
3
4
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
}

Now every time we save a JavaScript file, it will be formatted using Prettier automatically. Here is me formatting projectA/index.js file by saving it.

Prettier formats projectA/index.js

Notice the double quotes, semi-colons, etc — Prettier has applied the settings from projectA/.prettierrc.json. It also split long object across multiple lines to make it easier to read.

The same JavaScript code in projectB/index.js gets formatted by Prettier using different local settings and ends up looking different.

Prettier formats projectB/index.js

Single quotes, no semi-colons, trailing commas.

Tip: I love formatting code on «Save», but I hate formatting code on «Paste» — because it always adds extra line breaks. So I highly recommend the following VSCode settings

1
2
3
4
5
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.formatOnPaste": false
}

Format files from CLI

Formatting every file as you save it is nice, but we can also format ALL source files at once using Prettier CLI. In the package.json add a script to format files matching the mask and to write them back to disk.

package.json
1
2
3
4
5
6
7
8
9
{
"name": "prettier-config-example",
"scripts": {
"format": "prettier --write 'projectA/*.js' 'projectB/*.js'"
},
"devDependencies": {
"prettier": "1.18.2"
}
}

Run this NPM script and the files will be formatted to follow the Prettier style.

1
2
3
4
5
6
7
$ npm run format

> [email protected] format /Users/gleb/git/prettier-config-example
> prettier --write 'projectA/*.js' 'projectB/*.js'

projectA/index.js 30ms
projectB/index.js 10ms

If you want to format files with several extensions, list them using curly braces and commas. If you need to find all files in all subfolders, use ** syntax. For example, to format all .ts and .tsx files in the src folder use:

1
prettier --write 'src/**/*.{ts,tsx}'

Format staged files on commit

Whenever we work with files locally, we might accidentally commit them without proper styling. That’s where Git hooks and formatting staged files comes in handy. To consistently format all files before committing and then commit changes, I recommend using husky + lint-staged combination of tools.

Now configure pre-commit hook to run Prettier against staged JavaScript files. In the package.json set the following

package.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"devDependencies": {
"husky": "3.0.5",
"lint-staged": "9.2.5",
"prettier": "1.18.2"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.js": ["prettier --write", "git add"]
}
}

See lint-staged code formatting documentation.

If you try to commit changed JavaScript files, they will automatically be formatted and re-staged, ensuring only pretty JavaScript code is committed. In the Git commit shortcut output below, the «Running tasks…» messages comes from the lint-staged tool.

1
2
3
4
5
6
7
$ g done "add husky and lint-staged"
husky > pre-commit (node v12.4.0)
↓ Stashing changes... [skipped]
→ No partially staged files found...
✔ Running tasks...
[master 583b92a] add husky and lint-staged
2 files changed, 1513 insertions(+)

Of course, you can skip the Git pre-commit hook by committing with -n flag.

Update when using [email protected] and [email protected] the transformed files are added to the commit automatically. For example to format JavaScript and Markdown files on commit:

1
2
3
4
5
6
7
8
9
10
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,md}": ["prettier --write"]
}
}

Catch mis-formatted files on CI

Using stop-build

You can really enforce the formatting before pushing code to the central repository by running Prettier on CI and then detecting any changed files. Just run stop-build after running Prettier.

1
2
3
script:
- npm run format
- npx run stop-build

If any of the source files were reformatted by Prettier, the stop-only will detect changed source files using Git information and will exit with an error. It will list the changed files, something like this:

1
2
3
⚠️ there are 2 changed files
M projectA/index.js
M projectB/index.js

Using Prettier

Prettier has built-in command --check that validates code files against formatting. Using it from a script in package.json file:

1
2
3
4
5
{
"scripts": {
"check": "prettier --check 'projectA/*.js' 'projectB/*.js'"
}
}

Then on CI we can call the script right after npm install

1
2
3
script:
- npm install
- npx run check

Let’s say one of the files has not been formatted.

1
2
3
4
5
6
7
8
$ npm run check

> [email protected] check /git/prettier-config-example
> prettier --check 'projectA/*.js' 'projectB/*.js'

Checking formatting...
projectB/index.js
Code style issues found in the above file(s). Forgot to run Prettier?

Common problems

Nothing happens on save

You are saving a file in VSCode … and the code does not change. This could be due to three issues:

  1. Make sure local workspace settings have auto-format on save enabled. Open .vscode/settings.json file and confirm:
  • VSCode Prettier extension is configured as the default formatter.
  • Formatting on save is enabled
.vscode/settings.json
1
2
3
4
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
}
  1. Prettier extension might be disabled by VSCode. Make sure the word «Prettier» appears on the Status Bar and has check mark symbol next to it. To check:
  • Right click on the Status Bar. Make sure the «Prettier» extension appears there is displayed.

Show Prettier extension status

  1. Make sure there is a checkmark next to the «Prettier» in the Status Bar. Sometimes after enabling the extension, it is loaded, but not enabled.

Prettier extension is disabled for some reason

One thing I have noticed that sometimes saving a file enables Prettier if the .vscode/settings.json have the extension enabled for this workspace. For example in this animation I am saving the file with double quotes around a string, and magically the Prettier extension gets the check mark and does its job. Don’t ask.

Saving file enables Prettier and formats the code

If you click on the «Prettier» extension word in the status bar, it should open the Prettier output tab. It shows what Prettier extension executes, and often shows the problem. For example, the screenshot below shows that Prettier did not run because the project does not have Prettier configuration file like .prettierrc.

Prettier extension tab

If everything else fails, quit VSCode and start it again.

Code formatting is wrong

Here is a little animation that shows a file being saved with Prettier setting «trailingComma: true», yet the comma gets deleted somehow.

Saving file removes trailing comma

Check if there are OTHER code formatting extensions installed and disable them for this workspace. For some reason, VSCode can use globally installed extension overwriting local setting. Don’t ask. In my case, I had «Prettier-Standard» extension enabled globally. After disabling the «Prettier-Standard» for the current workspace, Prettier extension started working as expected.

Disabling Prettier-Standard extension

Why can’t VSCode save the list of disabled extensions in .vscode/settings.json?

Tips

Print width

Typically I use the default print width of 80 characters. But when I do my screen casts, I need both the code and the application side by side. Thus for those examples, I set the print width to 60.

.prettierrc.json
1
2
3
4
5
6
7
{
"trailingComma": "all",
"tabWidth": 2,
"semi": false,
"singleQuote": true,
"printWidth": 60
}

Print width of 60

Looks very nice!

Ignoring files

Sometimes you have files that should not be formatted: auto-generated source files, saved snapshots, etc. You can list file masks to ignore in file .prettierignore. For example, to ignore all JavaScript files in snapshots folders use

.prettierignore
1
2
3
# do not run Prettier against JavaScript files
# in "snapshots/" folders
**/snapshots/*.js

Saving without formatting

If you ever work in someone else’s project, please respect their formatting. In order to avoid reformatting the entire file when you save it from VSCode, save it without formatting. Run «Command + Shift + P» to open the Command Palette and type «save without» until you see «File: Save without Formatting» command — use that.

Save without formatting

Temporarily disable formatting

There is also an extension that temporarily disables format on save feature called Formatting Toggle. Install it in your VSCode and whenever you want to temporarily disable Prettier on save, click on the «Formatting» toggle in the status bar.

Save without formatting

Only format configured projects

In the VSCode global settings, set this option to only allow running Prettier in the folders with Prettier config file.

1
2
Prettier: Require Config
✅ Require a prettier configuration file to format

User global setting to require configuration file

I definitely recommend setting this global option to avoid accidentally changing how the code looks in the projects that do not want to use your or any Prettier settings.

Ignore parts of files

I love using range ignore to disable formatting parts of file. For example, to stop Prettier from reformatting Markdown tables use:

1
2
3
4
5
6
<!-- prettier-ignore-start -->
name | job
--- | ---
Joe | student
Mary | therapist
<!-- prettier-ignore-end -->

In code, you can tell Prettier to ignore the next AST node by adding // prettier-ignore comment. For example, in the next test we want to show the array input as a Tic-Tac-Toe board

1
2
3
4
5
6
7
8
9
10
11
it('returns O for second row of O', () => {


const squares = [
'X', 'X', null,
'O', 'O', 'O',
null, null, 'X'
]
const winner = calculateWinner(squares)
expect(winner).to.equal('O')
})

Use Eslint with Prettier

Prettier reformats JavaScript code to follow certain style, it does not check the meaning of the code. For example, Prettier happily reformats the following wrong code.

Prettier makes this wrong code look pretty

Static linters, like ESLint can catch the assignment to a constant variable, so we need both:

  • Prettier will reformat the code to be consistent in style
  • ESLint will analyze the meaning of code and catch potential problems

Disable style rules in ESLint

ESLint runs a long list of rules against the code, and some of these rules are stylistic, and can conflict with Prettier’s style. Thus we need to configure ESLint to skip those rules. This configuration is in module eslint-config-prettier. Install it

1
$ npm i -D eslint eslint-config-prettier

and can be added to your project .eslintrc.json file. ESLint will not run without a valid configuration file.

1
2
3
4
5
6
{
"env": {
"es6": true
},
"extends": ["eslint:recommended", "prettier"]
}

Now when you run ESLint against this file

projectC/index.js
1
const name = 'Joe'; name = 'Mary'

Then ESLint will catch the const assignment error; it will also catch that the variable name is never used after assignment.

1
2
3
4
5
6
7
$ npx eslint projectC/index.js

/prettier-config-example/projectC/index.js
1:7 error 'name' is assigned a value but never used no-unused-vars
1:21 error 'name' is constant no-const-assign

✖ 2 problems (2 errors, 0 warnings)

ESLint and React

If you want to check React code that uses JSX, import / export keywords, then install a plugin eslint-plugin-react

1
$ npx i -D eslint-plugin-react

And configure .eslintrc.json

1
2
3
4
5
6
7
8
9
10
{
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"env": {
"browser": true
},
"extends": ["eslint:recommended", "plugin:react/recommended"]
}

Integrate ESLint in VSCode

Since we are using VSCode, it makes sense to install ESLint VSCode extension called dbaeumer.vscode-eslint

Open Command Pallette with Command + P

1
ext install dbaeumer.vscode-eslint

Enable this extension in VSCode workspace settings

1
2
3
4
5
{
"editor.defaultFormatter": "dbaeumer.vscode-eslint",
"editor.formatOnSave": true,
"eslint.enable": true
}

JavaScript files should now show ESLint errors right inside VSCode editor.

ESLint errors

You can see these errors for yourself by opening projectC/index.js in VSCode from the example repo.

Run Prettier from ESLint

Since ESLint can detect and fix many of the errors it detects automatically, let’s tell ESLint to run Prettier too. Here is the recommended setup

Install ESLint Prettier config and plugin

1
$ npm i -D eslint-config-prettier eslint-plugin-prettier

Point ESLint at the recommended settings which include Prettier styles

projectD/.eslintrc.json
1
2
3
4
5
6
7
8
9
10
{
"env": {
"node": true,
"es6": true
},
"extends": ["eslint:recommended", "plugin:prettier/recommended"],
"rules": {
"no-console": "off"
}
}

Notice in the screenshot below how ESLint warnings in VSCode editor include style errors from Prettier.

ESLint shows Prettier errors

If we run ESLint with --fix flag, it will use Prettier to auto format code, solving both stylistic and semantic problems.

ESLint with Prettier fixes the code formatting

If you decide to use ESLint with Prettier rules and have configured husky to run lint-staged, point it at eslint --fix instead of prettier --write.

VSCode + ESLint + Prettier setup

Let’s configure VSCode to use ESLint to auto-fix found issues, including Prettier. The workspace settings use dbaeumer.vscode-eslint.

plugin v1 version (old)

1
2
3
4
5
6
7
{
"editor.defaultFormatter": "dbaeumer.vscode-eslint",
"editor.formatOnSave": true,
"eslint.enable": true,
"eslint.alwaysShowStatus": true,
"eslint.autoFixOnSave": true
}

plugin v2 version (current)

1
2
3
4
5
6
7
8
9
{
"editor.defaultFormatter": "dbaeumer.vscode-eslint",
"editor.formatOnSave": true,
"eslint.enable": true,
"eslint.alwaysShowStatus": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}

The animation shows how saving the file fixes both style and lint problems.

Using ESLint to auto-format and auto-fix issues on save

VSCode + ESLint + Prettier + TypeScript setup

ESLint can lint TypeScript files through typescript-eslint, and Prettier can format TypeScript code. Let’s set it up.

First, if you have previous installed TSLint extension vscode-tslint for VSCode, uninstall it — let ESLint do everything.

Second, install a new parser and plugin modules

1
2
3
4
5
$ npm i -D @typescript-eslint/parser @typescript-eslint/eslint-plugin
+ @typescript-eslint/[email protected]
+ @typescript-eslint/[email protected]
updated 2 packages and audited 576 packages in 2.42s
found 0 vulnerabilities

Then set the VSCode workspace settings to lint TypeScript files

.vscode/settings.json
1
2
3
4
5
6
7
8
9
10
11
{
"editor.defaultFormatter": "dbaeumer.vscode-eslint",
"editor.formatOnSave": true,
"eslint.enable": true,
"eslint.alwaysShowStatus": true,
"eslint.autoFixOnSave": true,
"eslint.validate": [
"javascript",
"typescript"
]
}

Set the ESLint options. Parsing files will be done using @typescript-eslint/parser, and we need @typescript-eslint plugin.

.eslintrc.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended",
"prettier/@typescript-eslint"
],
"rules": {
"no-var": "error"
}
}

And now you should see ESLint + Prettier errors and warnings in VSCode

ESLint error - no vars allowed

Style error - no semi-colons allowed

Note: there is a bug in VSCode + ESLint extension where Prettier is not found. If you open Prettier console you can see the error, there is an open issue

Prettier cannot fix the style automatically

So we see the lint and style errors, yet cannot reformat the code automatically on save. To work around this issue, use NPM script command.

package.json
1
2
3
4
5
{
"scripts": {
"fix-ts": "eslint --fix 'project-with-typescript/*.ts'"
}
}

Run this command and it should reformat the TS files and fix most ESLint issues.

Fixing TypeScript files

Use Prettier + ESLint + Cypress

One final touch. If you write Cypress end-to-end tests, there is an official cypress-io/eslint-plugin-cypress plugin that can catch some common test mistakes. You can find an example «test» in project-with-Cypress/index.js file.

First, install the plugin

1
$ npm i -D eslint-plugin-cypress

Then extend ESLint settings

project-with-Cypress/.eslintrc.json
1
2
3
4
5
6
7
8
9
10
11
{
"env": {
"cypress/globals": true
},
"extends": [
"eslint:recommended",
"plugin:prettier/recommended",
"plugin:cypress/recommended"
],
"plugins": ["cypress"]
}

Let’s say your test tries to get back an element using cy.get command.

project-with-Cypress/index.js
1
2
3
4
5
6
7

it('loads todos', () => {



const myApp = cy.get('#my-app')
})

This WON’T work — cy.get does not return an element, like a Promise, the found element will be passed down the command chain. Notice how ESLint shows an error if you try to assign the value of the cy.get command.

ESLint shows Cypress error

Catch exclusive tests

If you are writing Cypress or Mocha tests, you might accidentally leave it.only or describe.only exclusive tests. The build pipeline will be forever green giving you a false sense of confidence. You can catch exclusive tests using eslint-plugin-mocha.

See example in subfolder ‘project-with-mocha’ of the demo repo.

First, let’s use the Mocha plugin and set the environment and globals.

.eslintrc.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"env": {
"es6": true
},
"extends": [
"eslint:recommended",
"plugin:prettier/recommended",
"plugin:mocha/recommended"
],
"plugins": ["mocha"],
"globals": {
"describe": true,
"it": true
},
"rules": {
"mocha/no-mocha-arrows": "off"
}
}

Second, let’s try linting a spec file with an exclusive test

spec.js
1
2
3
4
5
6
7
8
9
describe('Mocha tests', () => {
it('has a test', () => {
expect(1).to.equal(1)
})

it.only('has another test', () => {
expect(2).to.equal(2)
})
})
1
2
3
4
5
6
$ ../node_modules/.bin/eslint .

/Users/gleb/git/prettier-config-example/project-with-mocha/spec.js
8:6 warning Unexpected exclusive mocha test mocha/no-exclusive-tests

✖ 1 problem (0 errors, 1 warning)

Nice, by default the mocha/no-exclusive-tests rules gives a warning. I recommend running lint step in pre-commit hook, where a warning is enough. From the pre-push Git hook I recommend making this rule an error.

1
2
3
4
5
6
$ ../node_modules/.bin/eslint . --rule 'mocha/no-exclusive-tests: error'

/Users/gleb/git/prettier-config-example/project-with-mocha/spec.js
8:6 error Unexpected exclusive mocha test mocha/no-exclusive-tests

✖ 1 problem (1 error, 0 warnings)

Common ESLint problems

Disable a rule

Sometimes you need to temporarily disable an ESLint rule. You can disable the rule for the entire file, a portion of a file, or just one line (my favorite!). For example, when showing a function signature, but not using the second argument config, we can prevent the ESLint from complaining:

1
2
3
4

module.exports = (on, config) => {
...
}

To disable a rule in the same line

1
2
3
module.exports = (on, config) => { 
...
}

To disable a rule in a portion of the file

1
2
3
4


...

To disable a rule in the entire file (but be careful!), add to the top of the file:

1

For more, see the blog post How to disable an ESLint rule

Errors shown for async keyword

Sometimes ESLint reports a problem around async keyword.

Misleading error after async keyword

ESLint’s parser does not understand that you are trying to use ES2017 syntax. Set the parser option in .eslintrc.json file to handle the async / await syntax.

1
2
3
4
5
6
7
8
9
{
"env": {
"es6": true,
"node": true
},
"parserOptions": {
"ecmaVersion": 2017
}
}

Other languages

Format other languages with Prettier

Prettier can format many languages: JavaScript, JSON, Markdown, HTML, CSS, etc. Here is formatting CSS for example.

Format CSS file using Prettier

Format JSON files with Prettier

You can configure Prettier and its VSCode extension to format your JSON files. Since there is already a default JSON formatter built into VSCode, you need to tell VSCode to specifically use esbenp.prettier-vscode to format JSON files. Here is a sample project settings file.

.vscode/settings.json
1
2
3
4
5
6
7
8
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.formatOnSave": true,
"json.format.enable": false
}

Format JSON files using Prettier

Use custom settings overrides

Here is a nice feature — you can set custom Prettier settings for some files. For example, we can use 2 spaces to indent by default, but 4 spaces to indent code blocks inside Markdown files, and 6 spaces to indent JSON files. Just because.

.prettierrc.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"trailingComma": "all",
"tabWidth": 2,
"semi": false,
"singleQuote": true,
"overrides": [
{
"files": "*.md",
"options": {
"tabWidth": 4
}
},
{
"files": "*.json",
"options": {
"tabWidth": 6
}
}
]
}

Let’s save a JSON file.

Format JSON files using Prettier with overridden settings

And here is saving a Markdown with a code block — which gets automatically formatted using Prettier with 4 spaces per tab.

Format code blocks inside Markdown files

Chrome extension

There is now Chrome Prettier extension that can format code blocks in text areas. Seems for now it is limited to StackOverflow and GitHub.

Run Prettier inside GitHub Action

GitHub Actions are now generally available — and they can do lots of interesting things, including running Prettier on every push and if there are any changes, committing the code and pushing it to the repo. In essence, they are doing the hard work for you! Read Trying GitHub Actions blog post for full details, here is the relevant CI YML file from bahmutov/gh-action-with-prettier repo.

.github/workflows/ci.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
name: Prettier
on: [push]
jobs:
build:
name: Prettier
runs-on: ubuntu-latest
steps:
- uses: actions/[email protected]
- uses: bahmutov/[email protected]
- run: npm run format
- run: git status


- uses: mikeal/[email protected]
env:

GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Beautiful, and on every push, if there are any format changes, the code gets updated and pushed, which you can see from the list of commits.

Prettier inside GitHub Action fixing code

With format on save, VSCode will automatically run the formatter whenever you save a file. This is a very handy feature as it keeps your code easy to read without manually run them through code linters or prettifiers.

In this article, we’re going to show you how to enable or disable format on save in VSCode, as well as troubleshoot common errors that prevent format on save from working properly.

Enable/Disable Format On Save

  1. Open up VSCode Command Palette by pressing Ctrl + Shift + P.
  2. Search and select Open Settings (UI). Just start typing and it will auto-fill. Once there’s a match, you can hit enter immediately, or manually click on the right option.
  3. Use the search box in the top to find Editor: Format On Save and tick in the checkbox in front of it to enable the feature. The changes takes place immediately, no need to restart VSCode.image-20210522223646168
  4. Format On Save only work with a formatter installed, and the editor must not be shutting down in the process. That means in case of a power outage, VSCode Format On Save might not work properly.
  5. Additionally, you can choose between formatting the whole file or just the modifications upon save by choosing file or modifications in Editor: Format On Save Mode section right below Editor: Format On Save.image-20210522224113835

Exclude programming format from Format On Save settings

By default, VSCode Format On Save settings are applied globally, regardless of what programming language you’re working with.

Most developers doesn’t code in one language, they may want to enable Format On Save on one programming language and disable it on the others. VSCode allows us to do that through something called language specific settings.

Let’s say we want to exclude JavaScript off of Format On Save settings. Follow these steps to do that.

  1. Open up VSCode Command Palette by pressing Ctrl + Shift + P.
  2. Search and select Open Settings (JSON) to open settings.json. Just start typing and it will auto-fill. Once there’s a match, you can hit enter immediately, or manually click on the right option. The settings.json contains the exact same settings the UI settings does. In other words, UI settings is just a representation of the JSON-formatted configuration in settings.json.image-20210522225155548
  3. If you enabled Format On Save before, you would see the following line in settings.json (your settings may look different than mine). image-20210522225750086
  4. Add these lines after "editor.formatOnSave": true to exclude JavaScript from auto-formatting upon saving.
    "[javascript]": {
       "editor.formatOnSave": false
    }
  5. Add a comma in the end of "editor.formatOnSave": true line to make the settings a valid JSON file. The result should look like this.
    {
       "editor.formatOnSave": true,
       "[javascript]": {
           "editor.formatOnSave": false
       }
    }

  6. You don’t have to add a new section for every single language. The [javascript] can include other languages as well, for example, [javascript,go]. For a full list of programming languages that VSCode supports and can automatically detected, see language identifiers page.
  7. Similarly, you can globally disable VSCode Format On Save altogether and enable it for only a handful of programming languages.
    {
       "editor.formatOnSave": false,
       "[javascript, python]": {
           "editor.formatOnSave": true
       }
    }

VSCode Format On Save with Prettier

By default, VSCode will use its own built-in formatters for a limited amount of programming language that it supports. If you prefer an opinionated code formatter like Prettier, you have to manually specify it in the settings.

Suppose that you’ve installed Prettier in VSCode. If you didn’t, consult our guide on installing plugins and themes in VSCode. One way to know whether Prettier is properly working is to look at the lower right corner of the editor, if you see Prettier section, then things are good.

image-20210524004353804

The next thing you’re going to do is opening Settings in UI mode either from the Command Palette or Edit > Preferences > Settings. Search for “formatter” in the search box on the top. Once you see Editor: Default Formatter settings, select esbenp.prettier-vscode from the drop down list.

image-20210524002403893

The settings takes place immediately. If you open settings.json now, you will see it in JSON mode.

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

To be able to enable Prettier for only a few languages, repeat the steps we used in the previous part of this article. In order to do that, edit the settings.json file so it would look like this:

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

Troubleshoot : VSCode Format On Save not working

In rare cases, VSCode Format On Save may stop working after an update or an OS installation. Below is a few possible solutions you can try.

  • Choose a default formatter instead of null – the default value. You might be surprised to learn that the settings may have changed on its own with the updates.
  • Uninstall other formatters one by one to see if anything causes the conflict.
  • Inspect settings.json, look for anything strange related to defaultFormatter. You may delete all and set them up all over again from scratch if needed.
  • Try to format your code manually by pressing Ctrl + Shift + P to open Command Palette and select Format Document. If your file is being properly formatted without any issues, it means there is something wrong in formatOnSave settings. You can try to make further debugging from this point.

VSCode hosts a bunch of other useful features which we’ve covered in our blog. Here’s a few of them if you’re interested :

  • How to quickly create a comment block in VSCode
  • How to quickly duplicate a line in Visual Studio Code
  • How to comment out multiple lines in Visual Studio Code
  • How to automatically indent your code in Visual Studio Code

Понравилась статья? Поделить с друзьями:
  • Prestashop ошибка 500
  • Pressure tank filling touareg ошибка устранение
  • Pressure error please turn off the instrument перевод
  • Pressure accumulator charging порше кайен как исправить
  • Press start button again ошибка киа