DEV Community

Cover image for VS Code: You don't need that extension part 2
Rob OLeary
Rob OLeary

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

VS Code: You don't need that extension part 2

This follows on from the post VS Code: You don't need that extension that I wrote last year.

There are builtin features and settings that ably do the work of many popular extensions. Perhaps, you do not need that extension!

Our remedies oft in ourselves do lie

- William Shakespeare

1. Wrap selected HTML in a tag

Sometimes, you want to wrap a block of HTML with another element when you are refactoring your HTML. This is awkward to do manually.

For example, in the code below, to wrap the 3 div elements in a main element, we would need to go to line 10 and type out an opening main tag. If we have auto closing tags setting turned on, we may have to delete this closing tag. Then, we need to go to line 26 and type out the closing main tag.

html example

It would be nice to just select the block and run a command to wrap it with the main tags.

Extensions

  • htmltagwrap (277K installs): "Wraps selected code with HTML tags"
  • html tag wrapper (165K installs): "wrap selected html tag by press ctrl+i, you can change the wrapper tag name simply too."

Feature

Emmet can do this for you. Select the code you want and run the command Emmet: wrap with abbreviation. You will be prompted for an abbreviation, you can just type the name of the tag you want. We just type "main" and hit enter.

emmet wrap abbreviation demo

If you wanted to wrap it with more than one tag and include a class, you can provide an Emmet abbreviation such as main>div.container, which will give you HTML like this:

<main>
    <div class="container">
        <div>Lorem....</div>
        <div>Animi...</div>
        <div>Velit...</div>
    </div>
</main>
Enter fullscreen mode Exit fullscreen mode

2. Bracket pair coloring

Styling of matching brackets pairs can help with identification of scope in your code. In particular, it is very popular for people to color brackets depending on their nesting level.

bracket colorization example

Quite a few extensions have filled this role in some way or another.

Extensions

  • Bracker Pair Colorizer (6.2M installs): "A customizable extension for colorizing matching brackets." The same author wrote Bracket Pair Colorizer 2 as a replacement with breaking changes and more emphasis on performance.
  • Bracket Pair Colorizer 2 (3.2M installs): "A customizable extension for colorizing matching brackets." It is now unmaintained.
  • Rainbow Brackets (1M installs): "Provide rainbow colors for the round brackets, the square brackets and the squiggly brackets. "
  • Highlight Matching Tag (945K installs): "Highlights matching closing and opening tags".
  • Subtle Match Brackets (88K installs): "Underlined matching brackets and more".

Feature

VS Code introduced native bracket pair coloring in v1.6.0 (August 2021). It is much faster than any of the extensions listed. You can read the "Bracket pair colorization 10,000x faster" blog for a deep dive.

Bracket pair coloring can be enabled by setting editor.bracketPairColorization.enabled to true.

demostration of bracket pair colorization for 6 indented levels

The bracket colors can be declared in a theme, or can be set through the setting workbench.colorCustomizations.

To set the colors for an installed theme through the workbench.colorCustomizations setting, you specify the name of the theme in square brackets, and then assign values to the properties as below. The property editorBracketHighlight.foreground1 refers to the first set of brackets, editorBracketHighlight.foreground2 to the second set of brackets, and so on. Also, there is the editorBracketHighlight.unexpectedBracket.foreground property for any extra brackets that are unmatched.

Bracket pair coloring settings summary

"editor.bracketPairColorization.enabled": true,
"workbench.colorCustomizations": {
    "[Panda Syntax]": {
      "editorBracketHighlight.foreground1": "#E6E6E6",
      "editorBracketHighlight.foreground2": "#FF75B5",
      "editorBracketHighlight.foreground3": "#19f9d8",
      "editorBracketHighlight.foreground4": "#B084EB",
      "editorBracketHighlight.foreground5": "#45A9F9",
      "editorBracketHighlight.foreground6": "#FFB86C",
      "editorBracketHighlight.unexpectedBracket.foreground": "#FF2C6D"
}
Enter fullscreen mode Exit fullscreen mode

Some of the aforementioned extensions enable you to apply more styles to the brackets, such as underlining and borders, currently this is not possible with this feature. However, there is a possibility for this to be added in the future because the bracket pair algorithm identifies brackets as tokens similar to how syntax highlighting works. Time will tell if this is something that will be added.

3. Indentation guides colorization

Indentation guides are vertical lines that outline the blocks of your code. They can help guide your eye to see how your code structured. VS Code refers to them as "brackt pair guides".

colored guides example

Extensions

  • Indent Rainbow (2.4M installs): "This extension colorizes the indentation in front of your text alternating four different colors on each step." Indentation colorization is based on tab size.

Feature

Since v1.61 (September 2021), the editor supports colors for indentation guides. VS Code refers to them as "bracket pair guides". They use the same colors as the bracket pair coloring feature discussed above by default.

Bracket pair guides can be enabled by setting editor.guides.bracketPairs to true, it is set to to false by default. There is a third option active to only show the indent guide for the active block. This setting should be used instead of the deprecated editor.renderIndentGuides setting.

As you can see from the example below, the guides are quite muted by default. It looks like the colors are destaurated.

indent guide colorization

You can enable highlighting of the indent guide for the current scope by setting editor.guides.highlightActiveIndentation to true. This should be used instead of the deprecated editor.highlightActiveIndentGuide setting.

As you can see from the example below, the active indent guide is shown in a brighter (more saturated) color.

active indent guide

There is also a setting editor.guides.bracketPairsHorizontal that controls if and when to render horizontal lines when a line of code crosses into another indentation level. It defaults to active.

horiztonal line indent guide

Similar to bracket pairs, the colors can be declared in a theme, or can be set through the setting workbench.colorCustomizations. You can change the color of the lines at each indent level through the properties editorBracketPairGuide.background{1,...,6} and editorBracketPairGuide.activeBackground{1,...,6} .

Indent guides settings summary

The relevent settings are:

"editor.guides.bracketPairs" : true,
"editor.guides.highlightActiveIndentation" : true,
"editor.guides.bracketPairsHorizontal" : "active",

"workbench.colorCustomizations": {
    "[Panda Syntax]": {
      "editorBracketPairGuide.background1": "#FFB86C",
      "editorBracketPairGuide.background2": "#FF75B5",
      "editorBracketPairGuide.background3": "#45A9F9",
      "editorBracketPairGuide.background4": "#B084EB",
      "editorBracketPairGuide.background5": "#E6E6E6",
      "editorBracketPairGuide.background6": "#19f9d8",

      "editorBracketPairGuide.activeBackground1": "#FFB86C",
      "editorBracketPairGuide.activeBackground2": "#FF75B5",
      "editorBracketPairGuide.activeBackground3": "#45A9F9",
      "editorBracketPairGuide.activeBackground4": "#B084EB",
      "editorBracketPairGuide.activeBackground5": "#E6E6E6",
      "editorBracketPairGuide.activeBackground6": "#19f9d8",
}
Enter fullscreen mode Exit fullscreen mode

4. Running and automating scripts (NPM, Gulp, Make, and others)

Most projects requires some tasks to be run like linting, testing, building, packaging, and deploying. Depending on the type of project it is, you may use different tools to handle this such as NPM, Grunt, Gulp, Make, and so on. While this is often something you do on the command-line, it can be handy to run some of these actions in the editor without switching context.

Extensions

  • NPM (2.7M installs): "This extension supports running npm scripts defined in the package.json file and validating the installed modules against the dependencies defined in the package.json."
  • Gulp Tasks (39K installs): "A gulp task visualization and execution extension for Visual Studio Code."
  • Make (31K installs): "Run Make easily."

Feature

VS Code has a Tasks feature. Tasks can be configured to run scripts you want inside VS Code through the command palette, you can customise how they are run, you can add a keybinding to them, you can run multiple scripts in a sequence, and you can run them automatically when you open a workspace.

VS Code can autodetect scripts for Gulp, Grunt, Jake, and npm. You can also run shell scripts, however they are not autodetected.

I will show you briefly how you can run NPM scripts as tasks. VS Code picks them up from your package.json.

Default build task

Pressing Ctrl+Shift+B or running the command Run Build Task will show you a picker of the autodetected tasks. For NPM, it narrows the list down for you:

build task command palette

Usually, the first option is the correct option.

Running a task

You can run a task through the Tasks: Run Task command. It will show you a list of the autodetected tasks from your workspace, and any custom tasks you created.

tasks

If you want to be run a task for a particular tool, you can use Quick Open, by pressing Ctrl + P or through the menu File > Go to File, you type "task" and hit space, and then the dropdown will show you the options for the different tools.

tasks

For my JavaScript project I pick "npm" and I get a list of my npm scripts.

npm tasks

Pick one and it will run the script.

Automate tasks

You can define custom tasks for your project in <project folder>/.vscode/tasks.json. You can create the file yourself, or you can run the Tasks: Configure Task command to build a template file for you by picking the option Create task.json file from template.

configure task command

You can configure a task to run when you open a project through the runOptions property. I discuss this in another article - How to run a command automatically in VS Code when you open a project. I often use this in projects to fire up a dev server whenever I open a project. This is what the tasks.json look like for that:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Run dev server on startup",
      "type": "shell",
      "command": "npm run dev",
      "windows": {
        "command": "npm run dev"
      },
      "presentation": {
        "reveal": "always",
        "panel": "new"
      },
      "runOptions": { "runOn": "folderOpen" }
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Adding a shortcut for a task

If you run a task frequently, you can define a keyboard shortcut for the task.

For example, to bind Ctrl+R to the my dev server task, I could add the following to the keybindings.json file:

{
  "key": "ctrl+r",
  "command": "workbench.action.tasks.runTask",
  "args": "Run dev server on startup"
}
Enter fullscreen mode Exit fullscreen mode

The args property should match the value of the label property from the tasks.json.


You can read the user guide on Tasks to learn more about tasks.

5. Formatting code

Consistent code formatting makes code easier to read, and saves your brain parsing cycles.

If you use many different languages, you will need some type of extension for formatting, but along the way you still may be using an extension that you actually don't need. It is not as cut and dry as the other items I have discussed, it is dependent on the particular languages you use. Let's get into it more specifically.

Extensions

  • Prettier (15M installs): Prettier is a very opinionated formatter with very few configuration options. It supports some languages by default: JavaScript, JSX, Angular, Vue, Flow, TypeScript, CSS, Less, SCSS, HTML, JSON, GraphQL, Markdown, and YAML. It has a plugin architecture to extend it to more languages.
  • Beautify (7.3M installs): Beautify uses js-beautify, which is a less opinionated formatter. It supports Javascript, JSON, CSS, Sass, and HTML. You can use a .jsbeautifyrc file to control the style settings.
  • HTML Format (300k installs)
  • JSON Formatter (30K installs)
  • Many, many more extensions listed in the "Formatter" category in the VS Code marketplace.

Feature

VS Code has builtin formatters for HTML, JavaScript, TypeScript, and JSON. This is a decent basis for frontend developers and JavaScript-oriented backend developers.

You may be wondering why CSS and CSS-like syntaxes are not on this list, I don't know why. What i do know is that the VS Code team does not plan to add one in the future. Like other languages that are not in this list, you will need an extension to provide formatting for that language. While it is tempting, particularly as a frontend developer, just to install Prettier because it covers a number of languages out of the box, there are tradeoffs with this. I will discuss this in the "Other languages" section below.

Settings for languages with builtin formatters

To use the builtin formatters, you can add the following settings:

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

I tried these out for a while and was pleasantly surprised. VS Code uses js-beautify under the hood, which is also used by the Beautify extension. So, you can expect similar results to that extension. 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 it without issues. I don't use React, so I can't comment how well React is formatted.

You cannot include a .jsbeautifyrc file in a project to control the formatting. However, there are equivalent formatting settings available. You will find formatting settings for each language with the naming convention of "<language-name>.format.<property-name>". Here are a few examples:

"html.format.wrapAttributesIndentSize": 2,
"html.format.templating": true,

"javascript.format.insertSpaceAfterCommaDelimiter": true,
"javascript.format.semicolons": "insert",
Enter fullscreen mode Exit fullscreen mode

There is an overview of the HTML formatting settings in the docs if you want to delve deeper.

Other languages

The tricky thing with formatters is that they involve considerable work to maintain, it is mosty left to independent devs to create the extensions to fill the gaps. Realistically, people are not able to maintain these as side projects, so the quality varies depending on how popular a language is. This is a weak spot for VS Code.

For other languages, you have a few different options:

  1. 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 (uses Prettier under the hood). You can use one of these as your formatter.
  2. You can install the Prettier extension or the Beautify extension to cover a few extra languages such as CSS. This is easy to do. However, these extensions are always loaded, regardless of the languages used in a project, because they use the onStartupFinished Activation Event in their configuration. This is wasteful of system resources, especially if you are working on backend projects that do not use to any of their default languages that these extensions format. Of course, you can disable the extension for a workspace to ensure that they do not load. If you have a decent computer, this may not bother you.
  3. If you want to use the Prettier extension for a language that is not supported out of the box such as Java, you need to install a Prettier plugin (a node package) as a development dependency for that project. It is awkward to have node packages in a non-JavaScript backend project. If you share a project with others, having 2 or more sets of dev dependencies is a headache.
  4. You can install a formatter that targets a particular language. You can search in the marketplace for a particular language in the "Formatter" category: https://marketplace.visualstudio.com/search?target=VSCode&category=Formatters&sortBy=Installs. These are not that common.

If you are a frontend developer, the big omission from the list of builtin formatters is for CSS and CSS-like syntaxes. The options for this are:

  • You can use the stylelint extension to cover you for both linting and formatting. Stylelint covers all CSS-like syntaxes. You can point to a global stylelint config in the VS Code settings.
  • If you use SASS (.sass files), you probably have installed the SASS extension for language support. This is also a formatter.
  • If you use one of the UI frameworks, you probably have installed an extension for language support, which are also formatters e.g. Vetur for Vue, and Svelte for VS Code for Svelte.
  • There does not seem to be a worthwhile dedicated CSS formatter, there is the JS-CSS-HTML Formatter but it has a backlog of serious issues.
  • If the above does not satisfy you, then maybe installing Beautify or Prettier is the best option.

For backend languages, you will find that most language support extensions are also formatters. You need to try them out to see if they are satisfactory. Of course, you could choose to use a linter to cover the formatting duties for you for these languages too.

Conclusion

Before you reach for an extension, see if VS Code can do it already. It sounds like an obvious move, but we are all probably guilty of doing it at one time or another. VS Code is adding features regularly, so it is worth checking the changelog every so often.


Thank you for reading! Feel free to subscribe to my RSS feed, and share this article with others on social media. 💌 🙂

Top comments (7)

Collapse
 
andreidascalu profile image
Andrei Dascalu

Quick Note:

  • Bracket Pair Colorizer (1&2) are no longer maintained and have been sporting that warning for a couple of months now. Many people I know (myself included) have been using it due to force of habit / settings sync (used it a long time ago and then go sync'ed in every VSC setup later on).
  • BPC recommends Blockman as an alternative (which is slightly different as in addition to coloring brackets, it also highlights the code block involved - it's a newer extension).
Collapse
 
robcannon profile image
Rob Cannon

Excellent article!

Collapse
 
robole profile image
Rob OLeary

Thank you 🙂🙏

Collapse
 
jjaimealeman profile image
Jaime Aleman

VERY well-done!

Thank you for the examples. So easy to copy/paste.

Collapse
 
agusmaris profile image
Agustin Mariscotti

Excellent, would you mind telling me which theme are u using?

Thanks!

Collapse
 
robole profile image
Rob OLeary • Edited

Thanks. The theme in the screenshots is Panda Syntax

Collapse
 
robole profile image
Rob OLeary

that sound dangersom