24

I'd installed prettier extensions and my json object definitions are now breaking lines after formatting. How can I avoid it? I want to keep inline object declarations.

for instance, before formatting:

  "properties": {
    "d0":  {"type":"boolean","default":false},
    "d1":  {"type":"boolean","default":false},
    "d2":  {"type":"boolean","default":false},
    "d3":  {"type":"boolean","default":false},
    "d4":  {"type":"boolean","default":false},
    "d5":  {"type":"boolean","default":false},
    "d6":  {"type":"boolean","default":false},
    "d7":  {"type":"boolean","default":false},
    "d8":  {"type":"boolean","default":false},
    "d9":  {"type":"boolean","default":false}
  }

after formatting:

  "properties": {
    "d0": {
      "type": "boolean",
      "default": false
    },
    "d1": {
      "type": "boolean",
      "default": false
    },
    "d2": {
      "type": "boolean",
      "default": false
    },
    "d3": {
      "type": "boolean",
      "default": false
    },
    "d4": {
      "type": "boolean",
      "default": false
    },
    "d5": {
      "type": "boolean",
      "default": false
    },
    "d6": {
      "type": "boolean",
      "default": false
    },
    "d7": {
      "type": "boolean",
      "default": false
    },
    "d8": {
      "type": "boolean",
      "default": false
    },
    "d9": {
      "type": "boolean",
      "default": false
    }
  }
jabacchetta
  • 45,013
  • 9
  • 63
  • 75
Daniel Santos
  • 14,328
  • 21
  • 91
  • 174
  • 1
    For reference, there's a long discussion on [single-line vs multi-line props wrapping in Prettier](https://github.com/prettier/prettier/issues/5501) with arguments for and against. You'd think this would just be an obvious option to configure (a toggle at least) but even that is being questioned as it conflicts with the idea that Prettier exists to promote a standard opinionated style. – Kalnode Jan 31 '20 at 13:15

5 Answers5

28

Why this behaviour happens:

Prettier breaks lines after a certain amount of characters specified by the Print Width config option.
This option can be changed but it should be noted that

Prettier recommends setting this option to < 80 to improve readability, (source)

For readability we recommend against using more than 80 characters:

In code styleguides, maximum line length rules are often set to 100 or 120. However, when humans write code, they don’t strive to reach the maximum number of columns on every line. Developers often use whitespace to break up long lines for readability. In practice, the average line length often ends up well below the maximum.

Prettier’s printWidth option does not work the same way. It is not the hard upper allowed line length limit. It is a way to say to Prettier roughly how long you’d like lines to be. Prettier will make both shorter and longer lines, but generally strive to meet the specified printWidth.

How to prevent this behaviour:

I'll go over some of the ways you can stop auto-wrapping:

  • Stopping auto-wrapping globally
  • Stopping auto-wrapping locally
  • Stopping auto-wrapping for a particular group of code

Stopping auto-wrapping globally

If you use the Visual Studio Code editor and the esbenp.prettier-vscode extension all you need to do to stop auto-wrapping is modify your global settings.json file. These are the steps that you need to follow.

1. Open settings.json
  • Use Ctrl+Shift+P to open the command palette.

enter image description here

  • From here type and select: > Preferences: Open Settings (JSON)

enter image description here

2. Set the option in settings.json

Appending this line to the end of your settings.json file means Prettier will only wrap the line when it exceeds 1000 characters (essentially never). You can change this number to preference, for reference the default is 80.

{
  "prettier.printWidth": 1000
}

Just make sure to save changes to the file and you are done!


Stopping auto-wrapping locally

This method works regardless of your IDE, we can create a .prettierrc file in the root of our project, and set the printWidth for our local project.

1. Create the .prettierrc file

Some older operating systems might try to prevent you from creating an extension only file. So when in the root of your project you can use this command to create your file.

Linux:

touch .prettierrc

Windows:

echo "" > .prettierrc
2. Set the printWidth

Add these lines to your .prettierrc file.

{
  "printWidth": 1000
}

Save the file and you're good to go,

Once again:

Appending this line to the end of your .prettierc file means Prettier will only wrap the line when it exceeds 1000 characters (essentially never). You can change this number to preference, for reference the default is 80.


Stopping auto-wrapping for a particular group of code

You can use a prettier-ignore comment to tell prettier not to format the following block of code, here are some examples from the prettier docs for JavaScript, HTML and CSS.

JavaScript
// prettier-ignore
matrix(
 1, 0, 0,
 0, 1, 0,
 0, 0, 1
)

This would otherwise be formatted to:

matrix(1, 0, 0, 0, 1, 0, 0, 0, 1);
HTML
<!-- prettier-ignore -->
<div         class="x"       >hello world</div            >

This would otherwise be formatted to:

<div class="x">hello world</div>
CSS
/* prettier-ignore */
.my    ugly rule
{

}

This would otherwise be formatted to:

.my ugly rule {
}

You can see the full list of language specific ignore strings here, as well as the options for ignoring a certain range of a file.


Note: Local settings in the .prettierrc file will override global settings in the settings.json file.

lejlun
  • 4,140
  • 2
  • 15
  • 31
  • 6
    I don't know why these answers get upvoted, none of the lines shown in the answer example are longer than 51 chars, so prettier.printwidth is not the cause here. – Lando Calc_rissian May 07 '22 at 01:13
  • 1
    The issue is more related to the parser that prettier is infering from, sometimes it is json, that makes the format as expected below the printwidth, but other times prettier is infering json-stringify as the parser, completely ignoring the printwidth setting. I will probably report this as a prettier issue once I investigate more about it. – Lando Calc_rissian May 07 '22 at 01:18
  • 1
    this solution is not working. – Ron Aug 29 '22 at 14:19
  • 1
    This is working in VSCode 1.81.1 Mac. Not sure why others saying this is not working or they may have another formatter other than Prettier changing their code. – Richard Fu Sep 01 '23 at 00:54
  • @RichardFu just to be clear, I just wanted to point out that the original question example didn't have more than 50 characters on any line, so the solution would hardly involve messing up with prettier's printWidth size, that is 80 by default. My point was: this answer is a solution to a different problem. If you read the original question carefully, it states issues with "json object", while leljun's answer is not specific to json Please take a look to my answer, you can easily reproduce the example and notice the difference with or without applying my suggested changes. – Lando Calc_rissian Sep 02 '23 at 17:38
2

In my case, I was experiencing the same issue, and after investigating the vscode output tab for prettier-vscode extension, I discovered that prettier was inferring the json-stringify parser automatically for that specific file, and increasing printWidth option had no effect at all.

My solution was forcing the json parser for that specific file, and then I could format as expected.

In .prettierc or whatever config method you use, add the overrides key:

        "overrides": [
            {
                "files": "yourfile.json",
                "options": { "parser": "json" }
            }
        ]
1

Prettier should only break lines up when they go beyond the print width that you have set (defaults to 80).

Assuming you're using this extension, experiment with the following setting:

{
  "prettier.printWidth": 80
}

If that doesn't work, go through and make sure you don't have any other code formatting extensions installed that might be taking precedence.

jabacchetta
  • 45,013
  • 9
  • 63
  • 75
1

In order Prettier "prettier.printWidth": XXX configuration would work, ensure your VS Code prettier formatter for the desired language is not overriden in VS Code user settings.

See the following extract from VS Code settings.json (to open Ctrl+Shift+P type "sett " -> select "Open User Settings (JSON)").

    "[json]": {
        "editor.defaultFormatter": "vscode.json-language-features"
    },
    "editor.defaultFormatter": "esbenp.prettier-vscode"

As you may note the more specific [json] key overwrites the default formatter for JSON files so that Prettier is not JSON files formatter.

Update the settings for the desired language (JSON in our case) to use the desired formatter (in this case either remove [json] key entry to use Prettier for any file, or change the JSON default formatter to Prettier). That should fix the issue.

Valentine Shi
  • 6,604
  • 4
  • 46
  • 46
1

I think this was not possible with prettier prettier version 2.6.0 in 2022, a singleAttributePerLine option was added. It will leave objects untouched if they are already on a single line, and fit in the printWidth option. More details here: https://prettier.io/blog/2022/03/16/2.6.0.html

you can set this option to false in prettier config, in .prettierrc.js for example:

// prettier.config.js or .prettierrc.js
module.exports = {
    singleAttributePerLine: false
};

It is supposed to work with HTML and JSX, but it worked with typescript also, I guess it will with json...

(strange the solution with printWidth / wrapping was upvoted so many times, even the example in the question fits in a printWidth of 80...)

mchelin
  • 11
  • 1