Let’s make a VS Code snippet from a Meme!

Lewis Munyi
3 min readJan 31, 2019

--

Behold the meme.

Browsing through the internet, I came across this very interesting meme. and thought to myself, “wouldn’t it be great if my editor could do this?” Well, turns out I could. And here’s how:

I will use Visual Studio Code, a free open-source text editor by Microsoft since it is the most popular development environment for web developers. VS COde comes with support for user snippets which is what we are going to use for this tutorial.

After downloading and installing it, open the command palette by holding down ctrl + shift + p then type Configure user snippets.

Command palette > Configure User Snippets

Type Javascript to launch the default javascript.json file.

Configure User Snippets > javascript

This will launch the default javascript.json file

javascript.json

We don’t need the commented text so I will delete that and define a new snippet. The new snippet will contain the following:

  1. Prefix: This is what we are going to type in the editor
  2. Body: The block of code that the prefix will be replaced with
  3. Description: A description of what the snippet does.

Create a new JSON object called “Stackoverflow Try-Catch” and inside it create the prefix, body & description strings/objects.

{
"Stackoverflow Try-Catch": {
"prefix": "",
"body": [],
"description": ""
}
}

Set the prefix and description to anything you want.

{
"Stackoverflow Try-Catch": {
"prefix": "trycatch",
"body": [],
"description": "An awesome try-catch statement"
}
}

Now we will write the body. Each line of code will be written as a new string

{
"Stackoverflow Try-Catch": {
"prefix": "try",
"body": [
"try {",
" // Something",
"} catch (error) {",
"window.open('https://stackoverflow.com/search?q=[js]' + error.message, '_blank');",
"}"
],
"description": "An awesome try-catch statement"
}
}

This works well enough, but we could make it even better. VS Code allows us to pre-select the cursor location using $ sign followed by a number. Eg; $1, $2, $3, $4 …. $x. The number one means that the cursor will automatically be placed in that position and will move to position 2 once the user hits TAB. $0 is where the cursor will rest once the user has reached the end.

We can also pre-select text blocks for a user to easily replace them with their own code, such as the comment in the try block. Eg; ${1: // Something}, ${2: else}This will move the cursor to that position and pre-select the comment. Nesting is also possible as we will see in this implementation. More on these can be found on their docs.

The final code will look like this. Feel free to edit it however you like!

Results:

Voila!

If you enjoy this quick tip, you can give it a 👏🏿or share it out. Thanks!

--

--