DEV Community

Cover image for VS Code - You don't need a formatting extension (Prettier and friends)
Rob OLeary
Rob OLeary

Posted on • Edited on • Originally published at roboleary.net

VS Code - You don't need a formatting extension (Prettier and friends)

In a previous post, VS Code: You don't need that extension part 2, I discussed how you may not need an extension for (prettily) formatting your code (see item 5). You can use the built-in formatters for a number of languages. However, at that time, the advice I gave came with some caveats.

VS Code has builtin formatters for HTML, JavaScript, TypeScript, and JSON. This is a decent basis for frontend developers and JavaScript-oriented backend developers. However, there was nothing for CSS and CSS-like syntaxes. A big omission in my opinion!

This has been rectified in v1.66 (March 2022). The built-in CSS extension now ships with a formatter. The formatter works with CSS, LESS, and SCSS. It is implemented using the JS Beautify library. ๐ŸŒŸ

Settings for languages with builtin formatters

To use the builtin formatters, you can add the following settings to your Settings.json:

"[html]": {
    "editor.defaultFormatter": "vscode.html-language-features"
},
"[javascript][javascriptreact][typescript]": {
    "editor.defaultFormatter": "vscode.typescript-language-features"
},
"[json][jsonc]": {
    "editor.defaultFormatter": "vscode.json-language-features"
},
"[css][scss][less]": {
    "editor.defaultFormatter": "vscode.css-language-features"
}
Enter fullscreen mode Exit fullscreen mode

This is using the multi-language syntax that was added in v1.63.2, in November 2021.

Since VS Code uses the JS Beautify library under the hood, which is also used by the Beautify extension, you can expect similar results to that extension. This may or may not to your taste, but it does a solid job.

Your mileage may vary for the formating of JSONC, it is asking the JSON Language Features extension to deal with โ€œillegalโ€ comments, but it appears to manage without issues. I donโ€™t use React, so I canโ€™t comment how well React code is formatted.

Settings added to control the formatting of CSS, LESS, and SCSS

You configure how the formatting is done with the following settings:

  • css.format.enable - Enable/disable default CSS formatter.
  • css.format.newlineBetweenRules - Separate rulesets by a blank line.
  • css.format.newlineBetweenSelectors - Separate selectors with a new line.
  • css.format.spaceAroundSelectorSeparator - Ensure a space character around selector separators '>', '+', '~' (for example, a > b).

The same settings also exist for Less and SCSS. Maybe more of JSBeautify's configuration options will be exposed later on. We will see, I guess!

Final word

For frontend developers and JavaScript-oriented backend developers, the builtin formatters should have you covered now. As long as you happy with the output, then you may not need another formatting extension.

And since, many language support extensions are also formatters e.g. Python, Language Support for Java by Red Hat, Ruby, YAML, XML Tools, Vetur for Vue, and Svelte for VS Code. Now, it is easier than ever to forgo using a dedicated formatter extension! ๐Ÿ†’


Feel free to subscribe to my RSS feed, and share this article with others on social media. ๐Ÿ’Œ

You can show your appreciation by buying me a coffee on ko-fi. ๐Ÿ™‚

Top comments (33)

Collapse
 
ravavyr profile image
Ravavyr

OR....just hear me out...

You could hit "tab" when typing and also the "," and "enter"....and get pretty much the same results. With some practice you'll get it all right automatically and you'll also understand your code better because it wasn't a tool that organized it for you. The experience of formatting it yourself helps your brain remember it better, just like taking notes in class helps you learn the material better. There's little to no effort to doing this as you go and it can be very beneficial to your skills as a developer in the long run.

Something to think about before you install that next helpful tool.

Collapse
 
danwalsh profile image
Dan Walsh • Edited

I tend to disagree that there is little to no effort in manually formatting your code. In my own experience, formatting code takes up precious cognitive load that I'd rather spend working through my code logic.

For example, I know I want to:

  • Terminate each line with a semicolon
  • Use four spaces per indentation, and
  • Wrap all arrow functions in curly braces

All of the above are just personal preferences, but I don't want to have to think about any of this. Instead, I want to focus on converting business logic into coding syntax, and having to pause every few moments to throw in an arbitrary semicolon or fix the indentation of an entire block just takes me out of "the flow".

I'd suggest taking the extension settings a step furtherโ€”configuring Prettier not only to auto-format your code on save, but to also display formatting suggestions inline using yellow wiggly underlines. That way you have the benefit of learning why a formatting rule is getting applied, as well as the auto-format on save. You get the learning plus the time savings.

You mention in a later comment that:

For me, when coding, especially javascript, it helps to do the formatting myself because it also helps me "see" the "scope" of my methods and classes, so my brain can quickly spot where a scope starts and ends, also helps me make less mistakes when creating new objects, or modifying existing stuff.

Again, I'd argue that extensions like Bracket Colorizer (which is now a built in function of VS Code) helps immensely with block scope visibility.

Lastly, your comment regarding "complex tasks" in relation to web dev is quite dismissive:

Now depending on what kinda coding/programming you guys do, i understand the "focusing on more complex tasks", but really, i've been doing this 16 years myself and in web dev there are few things that i would call "complex tasks".

Complex tasks come in all shapes and sizes. They can be laborious and intensive, such as refactoring a legacy component for use in a newer framework. They can be more investigative, such as debugging a complex pipeline build issue with Webpack. Or they might have nothing to do with the code at all, such as having to sporadically context switch between development tasks, support tasks, meetings and the other umpteen distractions flowing through the door. All of these things have something in commonโ€”they take up precious cognitive load and focus. Adding manual code formatting on top of that seems like an extra burden to me.

Work smarter, not harder. ๐Ÿค“

Collapse
 
ravavyr profile image
Ravavyr

Great response.

I still avoid Prettier like hell, because working for an agency i have to work with client code across various platforms, codebases, often in different languages, etc etc. Worse, some clients enforce their own rules like "standards js" or some other configurationg for formatting that i have to follow.

Getting yelled at by "avoiding insulting people here" because my formatting didn't match their is low on my list of things i like, so i look at the code i'm editing and make my changes match as best i can.

Funny thing, in some cases i make my formatting absolutely different on purpose because I want to come back later and go "This is my code, that is not my code" especially in really old applications that i have to still support, or when clients get to be a pain and nitpick every bug as "you made a change last week, this is your fault". Anywho, that's a different discussion altogether.

You're right, i was being dismissive with the "web dev is easy" bit.
Frankly, I'd say 99% of what we do is easy, once you've gotten good at it, or maybe it's "once you've seen enough bugs to recognize them before you know the details"
There are times when bugs stump people and can take days to resolve, but those are few and far between.
The industry is largely people with less than 10, or less than 5 years exp and a lot of things seem hard during those years, but with enough experience i think most of it is pretty damn easy.

eg. Centering a div is a nightmare for newbies, but a year or two in, you copy paste a solution you've used fifty times before and don't even think about it.
In JS you can say arrays and loops are hard when you start, but a few years in and you don't even think twice when using the various looping methods and you've realized everything is an object.
In PHP handling session variables, setting cookies, writing crons all seem complex, until you've done em a few dozen times.

As for VSCode extensions, i'd recommend checking out "indent-rainbow" , "power mode" for fun, and "indented block hightlighting". And yea the bracket colorizing they added is nice and useful.

I try to work smarter not harder :)
Whenever I get to code from scratch i write it as simple as possible with the goal being "Me or anyone else has to understand this 6 months or a year from now".

I avoid tools because the way i code hardly requires them. My frontend code requires no build tools, to deploy i use github actions, to debug i run the web pages, use browser dev tools, check the network tab and look at the console log. For backend i've got my server error logs configured and usually SSH in and go
"tail -20 /var/log/apache2/error.log" and fix whatever pops up in there.

I really think web dev has been made overly complex by implementing more and more "programming" things that work well for desktop applications and computer programs, but have only added weight and bloat to the web. Things it's never really needed. But again, that's a discussion for another time.

Have a good day :)

Thread Thread
 
pavelloz profile image
Paweล‚ Kowalski • Edited

Getting yelled at by "avoiding insulting people here" because my formatting didn't match their is low on my list of things i like, so i look at the code i'm editing and make my changes match as best i can.

Usually .prettierrc and/or .eslintrc files take care of that.
I always say: i dont care whats the code style, as long as its standarized and everyone has a software that does it for us (ie. no manual labor and thinking involved)

Collapse
 
stojakovic99 profile image
Nikola Stojakoviฤ‡

Umm, no. That's like saying there is a benefit for not using snippets for the things you already know pretty well. Sure, a junior student shouldn't use snippets in Visual Studio for for loops but learn how to write them, but if you're seasoned developer you get absolutely nothing by doing such trivial tasks by hand. On the contrary, you lose the time you could have spent solving the problem.

Collapse
 
jamesthomson profile image
James Thomson

My thoughts exactly. I've been writing code for too damn long to be manually formatting it these days. I can only imagine the amount of total hours wasted when I used to have to do this in the past.

I see it akin to not using a linter. Sure, I can do it without one, but having it allows me to free up my mental state for more complex tasks.

Thread Thread
 
ravavyr profile image
Ravavyr

Whatever floats your boats guys.
It's always personal preference in the end.

Copy/pasting snippets is obviously a time saver, but i think we all fall prey to having random things in our code we forgot about because we copy/pasted something and didn't take the time to review it properly, not because we suck at it, but because we were in a hurry, got sidetracked, pulled away, distracted, or who knows what else and since it "worked" when we got back, we never want back to fully clean it up, since it worked.

Now depending on what kinda coding/programming you guys do, i understand the "focusing on more complex tasks", but really, i've been doing this 16 years myself and in web dev there are few things that i would call "complex tasks".

Now, game dev, phooey, that's nothing BUT complex tasks lol.

Thread Thread
 
stojakovic99 profile image
Nikola Stojakoviฤ‡

You donโ€™t copy and paste snippets. You press a key and you get a snippets with the fields which you can change so you need to know what the snippet does before you use it. Iโ€™m not talking about copy and pasting random code from the Internet. That certainly isnโ€™t something you should do.

I donโ€™t know what exactly you did but people deal with complex tasks on the web too so I wouldnโ€™t underestimate the job of web developers.

Thread Thread
 
ravavyr profile image
Ravavyr

I do web dev for a living, 16 years of it, 99% of what we do is easy, once you get good enough at it. Every now and the a serious problem presents itself that takes more than a day to solve.
I don't underestimate what we do, working for an agency I see messed up code almost every day and fix bugs for the most part. I'm essentially a firefighter versus a builder. Most bugs are basic mistakes people make when tired or rushed.

Thread Thread
 
stojakovic99 profile image
Nikola Stojakoviฤ‡ • Edited

As I said, I'm not sure what exactly you're doing but I was not thinking just about messed up code. When you're working with the microservice architecture for example you can run into serious issues pretty quickly because of the complexity involved (like race conditions). Those are human mistakes but same human mistakes happen to other developers. But I can agree that on average, web development is easier than other branches (which still doesn't make doing everything manually justified if you ask me).

Collapse
 
robole profile image
Rob OLeary • Edited

Manual formatting is an alternative of course! If you gain by doing it yourself, then keep on trucking.

When I need to move code around, or copy and paste some code, then I find it is busy work to manually format. This was my experience when I had an old computer and just wrote code in a basic text editor.

When working with XML files recently, I had no automatic formatting available and did it manually at first. I don't particularly want to remember the contents of config files! There are times when it is always good to have it done for you.

Different strokes for different folks.

Collapse
 
ravavyr profile image
Ravavyr

I was talking more about code. XML i consider more like "forced markup" lol.
I can't blame you for wanting to auto-format XML if you're dealing with a bunch of it.

For me, when coding, especially javascript, it helps to do the formatting myself because it also helps me "see" the "scope" of my methods and classes, so my brain can quickly spot where a scope starts and ends, also helps me make less mistakes when creating new objects, or modifying existing stuff.

Collapse
 
davidhavlin profile image
davidhavlin

Manual formating is completely useless and waste of time.. but if you feel more like "hard coder" good for you

Collapse
 
ravavyr profile image
Ravavyr

I literally explained how it helps you write better code because you spend more time writing it and understanding it.

But if being a jerk about it makes you feel better, carry on, you don't need to listen to me, i don't need to listen to you.

Thread Thread
 
stefan_weinmann profile image
Stefan Weinmann

I would doubt that, because I use exactly the opposite approach. I deliberately let Formatter take over certain tasks and save myself the time of just doing it. That's what I love about go, gofmt is already there.

"Gofmt's style is nobody's favourite, but gofmt is everybody's favourite."

Collapse
 
gitcrackeruk profile image
Pawel Siwek

I strongly agree with you. There was some time when I have been spending more time for setting up prettier formatter than actual code. It can be done during development manually.

Collapse
 
ravavyr profile image
Ravavyr

It comes down to personal preference. I don't think the tools save me any time. Once in a while they catch a bug i missed that costs me a little time, but i don't see "tool using devs" being better/faster than "non tool using devs" in my day to day work.

In the end, good devs are always better/faster than not-as-good devs, regardless of the tools used. So really, personal preference always wins and we end up in lots of pointless arguments.

Did i mention Tabs over Spaces for life! ? :)

Collapse
 
th0rgall profile image
Thor Galle

Using less plugins & dependencies is a laudable goal, but as some people pointed out, I don't want to become overly dependent on VSCode for formatting.

Formatting should work just as well in other editors or as a CLI tool/library, for example in commit hooks. You could argue that the CSS mentioned solution here is also externally available, but I don't think the same counts for the built-in JS/TS formatter.

Another (small) problem with using the built-in formatter is that the formatting rules depend on your VSCode version. They may be somewhat configurable, but most rules are decided by VSCode and might change in future versions. If you reopen a 2-year-old file in the latest VSCode, can you guarantee will it be formatted in the same way?

What would solve this:

  • Having the VSCode formatters available as an efficient CLI too.
  • Having versioned VSCode formatter configurations, so you can lock down formatting behavior.

editorconfig helps with broad configuration in an editor-agnostic way. The Deno platform also took a good step with their code formatter, which is both available in their VSCode extension and as the deno fmt CLI tool.

But for node.js/frontend projects, I think I'm stuck with Prettier or Rome Biome for the moment.

Collapse
 
john__olson profile image
John Olson

For us, its a pre-commit hook to format with pretty-quick on all staged files. Use whatever IDE you want (although I recommend VScode for the team), but our code will be formatted the same regardless.

Collapse
 
ravavyr profile image
Ravavyr

And that works well too. If you work on a team and on a product/platform, one code base, autoformatting helps everyone stay consistent. I won't disagree there.

Once you start splitting projects and switching between teams and other products you'll quickly find the code doesn't keep the same formatting, even if you enforce the hell out of it, in the long term it won't stay that way, someone will mess it up along the way and you'll spend more time arguing about how to fix the formatting than it's even worth doing. Seeing this with a current client whose dev team spends more time doing code reviews than actually building anything.

Collapse
 
john__olson profile image
John Olson

We've been using nx.dev/ for our mono repo for all of our front-end work.

Collapse
 
c_b_d profile image
Carlota Dias

You deserve a coffee.

Collapse
 
robole profile image
Rob OLeary

Thanks Carlota :-)

Collapse
 
stojakovic99 profile image
Nikola Stojakoviฤ‡

This is okay if the whole team uses VS Code, but I'm much more comfortable in having a IDE agnostic specification regarding formatting (like .editorconfig).

Collapse
 
robole profile image
Rob OLeary • Edited

Ya when it comes to a team project, there are these considerations. In another post in this series, I spoke about project-specific settings.

I agree it is not cool to force someone to use a particular IDE in a team. Git commit hooks are used to remedy this also. It depends on the project. It is good to have simple and clear standards.

Collapse
 
brianmcbride profile image
Brian McBride

Code formatting is, obviously, strongly opinionated. If you are only working on your code and that is all that ever will be - go for whatever you want.

The more people who interact with your code - the more reason to use a very standarized code-formatter. Prettier seems to be the most used, at least in a lot of languages. You have newer languages like GoLang who put immediate thought into providing a formatter.

The reason to use a standard formatter is that it helps others in reading code. While people might disagree on how much to indent, where to break lines, etc... the fact is that a general format allows us all to recogize what we are looking at better.

Just like your post here. You used paragraphs, bulleted lists, headers, etc... You could have formatted things in your own special way I suppose. Instead you followed the conventions set by the other thousands of posts to Dev.to. A tool like Prettier just makes it easier for us all to follow the conventions that thousands of others are using as well.

Collapse
 
robole profile image
Rob OLeary

beyonce dance routine

Collapse
 
marblewraith profile image
Matthew Rath

This kind of "light touch" formatting is more akin to autocorrecting typo's with more granular control, and it's a welcome addition ๐Ÿ‘

Impossible to use prettier, it does weird shit to arrays and style selectors.

Earlier this year vscode added multi-lang definitions, you can significantly shorten the config required in settings.json, instead of the above do the following:

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

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

"[css][scss][less]": {
"editor.defaultFormatter": "vscode.css-language-features"
},

Collapse
 
robole profile image
Rob OLeary

Thanks for sharing the multi-lang syntax! I had wondered why it wasn't supported in the past! ๐Ÿค”

Collapse
 
gemcloud profile image
Gem Cloud

Question: "vscode.typescript-language-features" formatter *.js files?
I tested as below settings.
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode", // worked!
//"editor.defaultFormatter": "vscode.typescript-language-features" //Not worked?
},

"vscode.typescript-language-features" does not work for javascript file!?

Thanks in advance!

Collapse
 
robole profile image
Rob OLeary • Edited

Yes, that builtin extension formats JavaScript and TypeScript code.

If you want to configure the default formatter for a JavaScript file that is open, right-click inside and select the option "Format document with.." from the context menu.

That will show a quickpick in the command palette with the available formatters, you can select the option "Configure default formatter.." to set the default formatter. The second option for me is: "TypeScript and JavaScript Features". Selecting it will add this snippet to your Settings.json:

"[javascript]": {
        "editor.defaultFormatter": "vscode.typescript-language-features"
}
Enter fullscreen mode Exit fullscreen mode

Running the command "Format document" from the command palette should format your code then.

If it does not work for you, something else is probably up! Prob best to post your issue on Stackoverflow in that case.

Collapse
 
zirkelc profile image
Chris Cook

Prettier integrated into ESLint and automatically executed on File Save and Git Commit ๐Ÿš€