Post

Creating Code Snippets in Visual Studio Code

Draft updated on Invalid Date
Default avatar

By James Quick

Creating Code Snippets in Visual Studio Code

This tutorial is out of date and no longer maintained.

Introduction

If you’ve been using Visual Studio Code for any amount of time, you are probably already familiar with snippets. If you’re not familiar with them, according to the Visual Studio Code docs, snippets are “templates that make it easier to enter repeating code patterns”. That’s kind of vague to me, so what does that really mean? It’s actually simple. Snippets are shortcuts to write the code that you’re tired of writing.

Snippets are shortcuts to write the code that you’re tired of writing

For example, how often in JavaScript do we write console statements, for loops, etc. How often in HTML do we write the boilerplate code for an HTML5 document? In CSS, how often do we write the same code to define a style simply by changing the selector? All of these things are incredibly repetitive and take away from our productivity. So, snippets give you a shortcut (think a handful of letters) to complete a section of code.

Understand that snippets are context-aware, meaning if you are working in a JavaScript file, JavaScript snippets show up. If you’re working in HTML, HTML snippets will show up. In this article, we are going to focus on creating snippets in Visual Studio Code for JavaScript. We are going to take a look at existing snippets and then dive into how to create and customize them.

Existing Snippets in Visual Studio Code

Visual Studio Code has lots of snippets already built-in. The simplest example comes in the form of Emmet. Emmet is a plugin baked into VS Code that provides tons of snippets for HTML and CSS. If you haven’t already yet, go find a video on YouTube and check it out. It will seriously save you so much time!

Probably the most notable example of this is the snippet to create HTML5 boilerplate code. To get this boilerplate code, all you have to do is type ! and then TAB. That’s it!! That’s the beauty of snippets.

Visual Studio Code also has lots of other built-in snippets.

If you’re curious to see what snippets you can find, open a JavaScript file, type a letter, and see what pops up.

Note: Snippets are the ones with black boxes to the left.

Here’s what happens when I type for. Notice all of the lines with the black boxes to the left? Those are snippets!

Snippets 'for'

Let’s Create our First Snippet

Visual Studio Code keeps its snippets in a JSON file associated with a given language. In this example, we will work with the javascript.json file, which, you guessed it, keeps our snippets for JavaScript.

To find this file (on a Mac) go to your menu and click Code → Preferences → User Snippets.

Create code snippet

You will then be prompted to choose a language. Choose JavaScript.

Choose Language

This is the file where we can add snippets. A snippet is basically just an object with different properties. Here are the ones we care about.

  • name - self-explanatory
  • prefix - what we want the user to type to trigger the snippet
  • body - the content of the snippet (single string or array of strings for multiline snippets)
  • description - self-explanatory

Let’s start with a snippet for a one-liner console.log() statement. Here’s what it looks like.

"Console log": {
    "prefix": "clog",
    "body": "console.log('$1');",
    "description": "Log output to console"
}

“Console log” is the key/identifier/name for our object and the prefix and description are straightforward. Let’s talk about the body. Notice that it’s just a one-line string, and the thing that probably jumps out at you is the “$1”. This is called a tab stop.

Tabstops allows the user to tab between multiple locations in the snippet.

When a user activates the snippet, the cursor will automatically jump to the first tab stop. Now, save your javascript.json file, open up a test JavaScript file, type clog, and then TAB. Your cursor should automatically jump in between the quotes as defined by the TAB.

Testing clog snippet

Multiple Tabstops and Multiline Snippets

If there are more than one tabstops, the cursor will jump to the subsequent tabstop with every TAB pressed. If you define the same tabstop multiple times, the text for each will be updated at the same time. This allows you to give a variable a name that is reused throughout the snippet. You can also define the final cursor position (where you want the user’s cursor when they finish) by using $0. Here’s a good example, creating a for loop through an array.

A couple of things to note first…

  1. Instead of using $1 ($ and a number) we are using $ and a piece of text which acts as the placeholder text for you to replace.
  2. This is a multiline snippet. For multiline snippets, the body becomes an array with each line of the snippet becoming a string in that array.
  3. To format our code appropriately, we’ve added a \t to lines that need to be indented.
"For ": {
    "prefix": "forarr",
    "body": [
        "for (let ${index} = 0; ${index} < ${array}.length; ${index}++) {",
        "tconst ${element} = ${array}[${index}];",
        "t$0",
        "}"
    ],
    "description": "For Loop"
},

Copy this into your snippets file then try it out!

Forarr

Choices

Another useful feature is providing choices to the user. This means that instead of them having to type out something manually, they could choose from a list of relevant choices. Let’s take a look back at our clog snippet from earlier. What if we wanted to give the user the flexibility to write a console.error() or console.warning() instead of just console.log(). This is a great opportunity for choices. Here’s what that would look like.

"Console Choice": {
    "prefix": "conc",
    "body": "console.${1|log,warning,error|}('$2');",
    "description": "Log output to console"
}

conc snippet

Activate Snippet from Keybinding

One of the coolest features of Visual Studio Code is the ability to customize it. One of the ways to do so is to override the default keybindings. Because of this, we could actually trigger one of our snippets from a keybinding instead of typing out the prefix to the snippet.

To edit your keybindings, go to the menu bar and click Code → Preferences → Keyboard Shortcuts.

Visual Studio Code keybindings

This gives you a semi-interactive file to work with, but we can add overrides manually by clicking the keybindings.json link at the top of this file. Once you do, you’ll get a side-by-side view of the default keybindings.json file and the one where you can override bindings.

Visual Studio Code keybinding manual override

Similar to how we define snippets, keybinding overrides are as simple as adding an object to the JSON file with three key properties.

  • Key - the key combination
  • Command - what we want to happen
  • When - when should this keybinding work (when the user is editing text? working in the built-in terminal?)

To trigger a snippet, we need one additional property called args. Args is an object itself with two properties, langId, and name.

  • langId - the language identifier (think JAVASCRIPT.json)
  • name - the name of the snippet we want to trigger

So here’s what it looks like to trigger a console log using the combination CMD+C L", which means pressing COMMAND` and ‘C’ keys together followed by the ‘L’ key.

{
    "key": "cmd+c l",
    "command": "editor.action.insertSnippet",
    "when": "editorTextFocus",
    "args": {
        "langId": "javascript",
        "name": "Print to console"
}

Save the keybindings.json file and try it out!

Conclusion

From here, you’ve got all the basics. Choose the language that you’re working with and edit its JSON file. Each snippet you want to add is a key-value pair with the key being the name of the snippet and the value being the actual snippet itself. The snippet itself has three main properties: prefix, body, and description. Tabstops gives you complete control over tabbing through the snippet and replacing placeholder text with the real deal.

Take a look at the Visual Studio Code Extension Marketplace where you can find lots of predefined templates so that you don’t have to write them all yourself.

Resources

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
James Quick

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel