How to tell VScode to format file-type A as file-type B, while preserving syntax highlighting? How to tell VScode to format file-type A as file-type B, while preserving syntax highlighting? vue.js vue.js

How to tell VScode to format file-type A as file-type B, while preserving syntax highlighting?


Vetur currently doesn't support switching to the built-in HTML formatter, but you could request that as a new feature in Vetur's issues.

Since the root problem seems to be the collapsing of newlines, I propose different solutions that address only that problem:

  • Switch Vetur's HTML formatter to js-beautify-html, and configure it to preserve newlines
  • Surround the newlines with ignore-comments
  • Disable Vetur's HTML formatting

Option 1: Use js-beautify-html

In VS Code preferences, set Vetur's HTML formatter to js-beautify-html:

screenshot of <code>js-beautify-html</code>

Then in settings.json (Choose Preferences: Open settings (JSON) from command palette), add the JSON block shown below. The key is to set max_preserve_newlines to a high number that allows your desired number of newlines.

"vetur.format.defaultFormatterOptions": {    "js-beautify-html": {        "max_preserve_newlines": 10000, // Maximum number of line breaks to be preserved in one chunk (0 disables)        "preserve_newlines": true // Whether existing line breaks before elements should be preserved    }}

Option 2: Use ignore-comments

The advantages of ignore-comments:

  • Disables formatter/linter while also documenting intentional whitespace, which is important for readers/maintainers
  • Can be easily enabled/disabled per section of code

Vetur's default HTML formatter is prettyhtml, which internally uses prettier, so you could utilize Prettier's ignore-comments:

<div><!-- prettier-ignore-start --><!-- prettier-ignore-end -->    <div>foo</div>    <div>bar</div></div>

If you switch the HTML formatter to js-beautify-html, use the corresponding ignore-comments:

<div><!-- beautify ignore:start --><!-- beautify ignore:end -->    <div>foo</div>    <div>bar</div></div>

Option 3: Disable Vetur's HTML formatting

Setting Vetur's HTML formatter to none in settings would disable the formatter for HTML sections in *.vue files. While this resolves the unwanted formatting of collapsing newlines, it has the obvious side effect of disabling all formatting in Vue templates, which might be acceptable for your usage.


To tell VScode to format file-type A as file-type B

  1. open your file in vscode
  2. Ctrl+Shift+P (or View -> Command Palette from the menu)
  3. and then type Change Language Mode
  4. type the name of programming language (for exemple sql,C++ ...)