Prettier Setup

This module guides you through setting up Prettier for consistent code formatting in your projects. Learn how to install, configure, and integrate Prettier with your development environment to enhance code quality and maintainability.

Summary content goes here.


Overview

  • Prettier is an opinionated code formatter that supports many languages and integrates with most editors.
  • It enforces a consistent style by parsing your code and re-printing it with its own rules.
  • This helps reduce debates about code style and allows developers to focus on writing code.
  • Prettier can be used with vscode by installing this extension.

Installation

Follow the instructions on the above link provided to install the extension. Then create two empty files in the root of your project.

  • .prettierrc - This file contains the configuration options for Prettier.
  • .prettierignore - This file specifies files and directories that Prettier should ignore.

To make sure it works well with the project add the following settings to your settings.json file in vscode.

 1{
 2  "editor.formatOnSave": true,
 3  "editor.defaultFormatter": "esbenp.prettier-vscode",
 4  "[javascript]": {
 5    "editor.defaultFormatter": "esbenp.prettier-vscode"
 6  },
 7  "[typescript]": {
 8    "editor.defaultFormatter": "esbenp.prettier-vscode"
 9  },
10  "[json]": {
11    "editor.defaultFormatter": "esbenp.prettier-vscode"
12  },
13  "[markdown]": {
14    "editor.defaultFormatter": "esbenp.prettier-vscode"
15  },
16  "[Yaml]": {
17    "editor.defaultFormatter": "esbenp.prettier-vscode"
18  }
19}

Configure Prettier

Add the following configuration to your .prettierrc file.

1{
2  "singleQuote": true, # Use single quotes instead of double quotes
3  "proseWrap": "always", # Wrap text as needed
4  "endOfLine": "lf" # Use line feed for line endings
5}

The above setting applies to all types of files. If you want to have specific settings for specific file types, you can use the overrides option.

 1{
 2  "singleQuote": true,
 3  "proseWrap": "always",
 4  "endOfLine": "lf",
 5  "overrides": [
 6    {
 7      "files": "*.md",
 8      "options": {
 9        "proseWrap": "preserve", # Preserve existing wrapping in markdown files
10      }
11    }
12  ]
13}

Test Prettier

Open a markdown file and add some unformatted content. Save the file and see if it gets formatted automatically. If nothing happens, watch the output panel in vscode and select Prettier from the dropdown to see if there are any errors or what the Prettier server is doing. It should show some activity like the shown below.

1["INFO" - 12:15:40] Formatting completed in 7ms.
2["INFO" - 12:19:36] Using config file at /home/....../.prettierrc

The above log indicates that Prettier is working correctly. To make sure that it formats the file correctly you will see other logs like the one below.

 1["INFO" - 12:22:38] Formatting file:///home/ag-sayyed/Documents/projects/vscode-setups/vscode-lint-format/tech-tests/test-markdown/broken-headings.md
 2["INFO" - 12:22:38] Using config file at /home/ag-sayyed/Documents/projects/vscode-setups/vscode-lint-format/.prettierrc
 3["INFO" - 12:22:38] PrettierInstance:
 4{
 5  "modulePath": "/home/ag-sayyed/Documents/projects/vscode-setups/vscode-lint-format/node_modules/prettier/index.cjs",
 6  "messageResolvers": {},
 7  "version": "3.6.2"
 8}
 9["INFO" - 12:22:38] Using ignore file (if present) at /home/ag-sayyed/Documents/projects/vscode-setups/vscode-lint-format/.prettierignore
10["INFO" - 12:22:38] File Info:
11{
12  "ignored": false,
13  "inferredParser": "markdown"
14}
15["INFO" - 12:22:38] Detected local configuration (i.e. .prettierrc or .editorconfig), VS Code configuration will not be used
16["INFO" - 12:22:38] Prettier Options:
17{
18  "filepath": "/home/ag-sayyed/Documents/projects/vscode-setups/vscode-lint-format/tech-tests/test-markdown/broken-headings.md",
19  "parser": "markdown",
20  "singleQuote": true,
21  "proseWrap": "preserve",
22  "endOfLine": "lf"
23}
24["INFO" - 12:22:38] Formatting completed in 7ms.

It informs us number of things like the config file being used, the parser being used, the options being applied and the time taken to format the file.

  • The meessage Using ignore file (if present) at ... tells us that the .prettierignore file is being used, if present.
  • The message File Info: { "ignored": false, "inferredParser": "markdown" } tells us that the file is not being ignored and the parser being used is markdown Which is not explicitly mentioned in the config file. Prettier infers the parser based on the file extension and shows in the log.

Test Markdown Frontmatter

Add the following content to a markdown file named testBadFormat.mdand save it.

1---
2test:
3  - test
4 test
5---
6
7Test

The above content has bad indentation in the frontmatter. If your linting is working corectly, it should show the marker indicataing the error, also in PROBLEMS panel you should see the error with explanation.

Fixing the Error

The above error can not be fixed automatically by Prettier for the reason mentioned below:

  1. Prettier requires the syntactically valid YAML content to be present either in a .yaml file or in the frontmatter of a markdown file to be able to format it.
  2. If the YAML content is invalid, Prettier will not be able to fix the indentation issues.

When trying to format a yaml file, it does not format. If you look closely to the message generated in a PROBLEMS panel, it says the following along with the settings sused for formatting.

 1["INFO" - 13:57:59] Prettier Options:
 2{
 3  "filepath": "/home/ag-sayyed/Documents/projects/vscode-setups/vscode-lint-format/tech-tests/test-yaml/testYaml-01.yaml",
 4  "parser": "yaml",
 5  "tabWidth": 2,
 6  "useTabs": false,
 7  "singleQuote": true,
 8  "proseWrap": "always",
 9  "endOfLine": "lf",
10  "embeddedLanguageFormatting": "auto"
11}
12["ERROR" - 13:57:59] Error formatting document.
13["ERROR" - 13:57:59] All collection items must start at the same column (1:1)
14> 1 | test:
15    | ^^^^^
16> 2 |   - test
17    | ^^^^^^^^^
18> 3 |  test
19    | ^^^^^^^^^
20> 4 |
21    | ^^
22SyntaxError: All collection items must start at the same column (1:1)
23> 1 | test:
24    | ^^^^^
25> 2 |   - test
26    | ^^^^^^^^^
27> 3 |  test
28    | ^^^^^^^^^
29> 4 |
  • The above log is shown when a yaml file is formatted. If we try to format the same content in a markdown file, it does not show any error in the output panel but behaves as if it has done the formatting successfully. It all happens due to the fact that the errors which are syntactically invalid are not fixed by either Prettier or the other extension used for linting the yaml content in the frontmatter of a markdown file.

Following is the output shown in the PROBLEMS panel when the above content is formatted in a markdown file.

 1["INFO" - 14:05:18] Formatting file:///home/ag-sayyed/Documents/projects/vscode-setups/vscode-lint-format/tech-tests/testYamlFmt/testBadFormat.md
 2["INFO" - 14:05:18] Using config file at /home/ag-sayyed/Documents/projects/vscode-setups/vscode-lint-format/.prettierrc
 3["INFO" - 14:05:18] PrettierInstance:
 4{
 5  "modulePath": "/home/ag-sayyed/Documents/projects/vscode-setups/vscode-lint-format/node_modules/prettier/index.cjs",
 6  "messageResolvers": {},
 7  "version": "3.6.2"
 8}
 9["INFO" - 14:05:18] Using ignore file (if present) at /home/ag-sayyed/Documents/projects/vscode-setups/vscode-lint-format/.prettierignore
10["INFO" - 14:05:18] File Info:
11{
12  "ignored": false,
13  "inferredParser": "markdown"
14}
15["INFO" - 14:05:18] Detected local configuration (i.e. .prettierrc or .editorconfig), VS Code configuration will not be used
16["INFO" - 14:05:18] Prettier Options:
17{
18  "filepath": "/home/ag-sayyed/Documents/projects/vscode-setups/vscode-lint-format/tech-tests/testYamlFmt/testBadFormat.md",
19  "parser": "markdown",
20  "tabWidth": 2,
21  "useTabs": false,
22  "singleQuote": true,
23  "proseWrap": "preserve",
24  "endOfLine": "lf",
25  "embeddedLanguageFormatting": "auto"
26}
27["INFO" - 14:05:18] Formatting completed in 4ms.
28["INFO" - 14:06:30] Using config file at /home/ag-sayyed/Documents/projects/vscode-setups/vscode-lint-format/.prettierrc

Formatting with yaml-fm-lint CLI

  • Since we are using yaml-fm-lint extension for linting the frontmatter content, we can use its CLI to format the content in the frontmatter of a markdown file to see if it fixes any issues.
  • First install it locally in your project using the following command:
1npm install yaml-fm-lint --save-dev
  • Then add the following script to your package.json file.
1"scripts": {
2   "fmlint": "yaml-fm-lint --config=yaml-fm-lint.json -r --oneline -c",
3   "fmlint:fix": "yaml-fm-lint --config=yaml-fm-lint.json -r --oneline -c --fix"
4}

Where yaml-fm-lint.json is the configuration file for the yaml-fm-lint CLI. You can create it in the root of your project with the following content:

1{
2  "disabledAttributes": [],
3  "extraExcludeDirs": ["scripts"],
4  "excludeFiles": ["_index.md", "test-cspell.md", "Readme.md"],
5  "mandatory": false,
6  "requiredAttributes": [],
7  "extensions": [".md"],
8  "includeDirs": []
9}
  • Now run the following command to see if it shows any issues in the frontmatter of the markdown files.
 1# npm run fmlint <path/to/folder/or/file>
 2# npm run fmlint tech-tests/testYamlFmt/testBadFormat.md
 3$ npm run fmlint tech-tests/testYamlFmt/testBadFormat.md
 4
 5> vscode-lint-format@1.0.0 fmlint
 6> yaml-fm-lint --config=yaml-fm-lint.json -r --oneline -c tech-tests/testYamlFmt/testBadFormat.md
 7
 8YAML-Error: <bad indentation of a mapping entry> tech-tests/testYamlFmt/testBadFormat.md:4:2
 91 error found.
10Linting took: 6.916ms
  • Now run the following command to fix the issues in the frontmatter of the markdown files.
1$ npm run fmlint:fix tech-tests/testYamlFmt/testBadFormat.md
2$ npm run fmlint:fix tech-tests/testYamlFmt/testBadFormat.md
3
4> vscode-lint-format@1.0.0 fmlint:fix
5> yaml-fm-lint --config=yaml-fm-lint.json -r --oneline -c --fix tech-tests/testYamlFmt/testBadFormat.md
6
7YAML-Error: <bad indentation of a mapping entry> tech-tests/testYamlFmt/testBadFormat.md:4:2
81 error found.
9Linting took: 4.581ms

Though the above command is still not able to fix the issue yet it can fix other issues like missing mandatory attributes, missing required attributes etc. which are not present in this case.

Conclusion


FAQs