Explain Codes LogoExplain Codes Logo

How do you stop Prettier in VS code splitting attributes onto multiple lines?

javascript
best-practices
formatting
prettier
Alex KataevbyAlex Kataev·Jan 24, 2025
TLDR

To retain HTML attributes on one line in VS Code with Prettier, increase the printWidth value in the Prettier settings:

{ "printWidth": 120 }

A greater printWidth equals longer lines before Prettier begins to wrap your code, thus keeping your attributes together.

Manual formatting: Control the Reins

For more control over Prettier's output:

  • Disable Format On Save: Prevent automatic formatting upon saving. Useful when you want to manually manage the formatting.

  • Use Keyboard shortcuts: Alt+Shift+F (Windows/Linux) or Option+Shift+F (macOS) in VS Code for manual formatting. Not magic, but close!

  • Configure formatting preferences: Tweak your .prettierrc.json for more custom formatting. Prettier has as many moods you give it!

  • Control specific sections: Use <!-- prettier-ignore --> above the HTML block you want Prettier to step away from. This is a nifty magic spell Prettier obeys!

Incremental fine-tuning: Your Settings Mastered

Tweak your setting's bit by bit for the best-fit customization:

  • Start with a printWidth of 80-100 for best readability, then tweak it upwards until you're happy with the result.

  • Go to the Prettier playground to experiment with your settings in a visually engaging environment. Much game, such play, wow learning!

  • Perform incremental tweaks: Play around with different settings and review the output until you hit the bulls-eye.

  • Make use of the .prettierrc.json for universally-consistent rules across your devices or team endeavors.

Broaden your horizon: Not Only Prettier

If Prettier is somewhat falling short for your needs:

  • Sync up with your team: Discuss and decide on a communal .prettierrc.json file to maintain consistent styling.

  • Stay updated: Regularly check for new releases and plugins that might improve Prettier's feature set.

  • Use alternatives: Explore different formatting tools and extensions if Prettier doesn't quite hit the mark for your unique requirements.

Handling updates: When the Furniture Moves

New Prettier updates sometimes move the furniture around. Have a plan to manage the chaos:

  • Versioned .prettierrc.json: Lock configurations to a Prettier version to stay consistent.

  • Continuous integration: Set up a CI process that verifies whether the code style matches your project's .prettierrc.json rules. It's like a bouncer at a club, but for your code!

  • Legacy lives: If working on a project with a lot of legacy code, selectively apply Prettier to the files you are actively changing.