简体   繁体   中英

Stop Prettier formatter from putting each HTML tag on its own line in React JSX files?

When I format an HTML file using prettier, it looks like this:

<nav>
  <ul>
    <li><a href="#" title="Home">Home</a></li>
    <li><a href="#" title="About">About</a></li>
    <li><a href="#" title="Sign Up">Sign Up</a></li>
    <li><a href="#" title="Contact">Contact</a></li>
    <li><a href="#" title="Careers">Careers</a></li>
  </ul>
</nav>

But when I put the same tags in a JSX file, it reformats it like this:

import React from "react";

const Demo = () => {
  return (
    <nav>
      <ul>
        <li>
          <a title="Home">Home</a>
        </li>
        <li>
          <a title="About">About</a>
        </li>
        <li>
          <a title="Sign Up">Sign Up</a>
        </li>
        <li>
          <a title="Contact">Contact</a>
        </li>
        <li>
          <a title="Careers">Careers</a>
        </li>
      </ul>
    </nav>
  );
};

export default Demo;

How can I stop this behavior? It happens even with a high value for prettier.printWidth

After more reading I've concluded this isn't possible. HTML is whitespace sensitive so it is retained, but since JSX isn't it gets autoformatted always and Prettier has no option to keep tags on the same line.

You should be able to curve this by using

"bracketSameLine": true

In the prettier config JSX Brackets

This also could be of some help How to disable prettier settings creating new line of > of html tag?

Prettier has the option printWidth . You can change it to something large value in settings.json . It's a bit of a stretch, but it works.

"prettier.printWidth": 140

I found a solution, make sure file is jsx and on bottom right is selected "JavaScript React".

With Prettier installed copy this to your settings.json:

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

Basically you're telling vs code to format JSX Files with the VS Code typescript mode instead of Prettier. (this won't break the html tags in the components)

Normal JS files will sill be formatted with prettier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM