DEV Community

Cover image for Write Your Own Snippets in VSCode
Lucas Perez
Lucas Perez

Posted on

Write Your Own Snippets in VSCode

Everyone has its own way of learning things. What I know about myself is that little shortcuts often get in the way at the beginning. One example are snippets and VSCode extensions that add those snippets.

What Are Snippets?

Snippets are just a piece of text (or code, in our case), a little extract from something bigger. They are very helpful to avoid repetition. If you constantly have to write a piece of code, you surely thought about copying and pasting a big chunk of boilerplate code (I know I have). Well, those are basically snippets.
Now, wouldn't it be great if we could automate the process of pasting those chunks of code? Like this:
Nice snippet example

Here I just typed some kind of shortcut and pressed tab, pretty much like auto completion, but for something bigger.

No Need For VSCode Extensions!

I recently started studying React and decided that to be productive I should add some kind of extension full of snippets, just like in the videos I was watching.

The problem is that now my coding environment got full of autocomplete suggestions that would just return a bunch of text. Many shortcuts that I did not know about would sometimes randomly make me pop huge code extracts when I was trying to write something completely unrelated. Snippets that I didn't know their uses. And then I realized that I was overwhelmed with many useful shortcuts that were not meaningful for me at the moment. I did now know why a particular Snippet existed in the first place.
Too many snippets!
List of all the snippets of a particular extension

If I don't know why a shortcut is useful, it is not useful for me and I shouldn't use it.

Sometimes I think of it like a game. I have to code a certain amount to unlock a particular snippet. I can only use it when I got tired of writing it by hand.

Create Your Own Snippets

VSCode already has by default some snippets, and that is really nice.
But, you can create your own custom Snippets, and it is actually pretty easy!
This has the immediate benefit of only populating your environment with snippets that you know that exist, you know what is it's purpose and how to use them.
Also, it ensures that you really learn the hard way before actually gifting yourself an easy alternative, meaning that you can code anywhere, and not just in your particular computer.
Finally, you can customize them according to specific needs if necessary.

So, How Do We Do It?

Start your VSCode and open the Command Palette (CTRL + SHIFT + P by default) and write snippet to see the options that appears:
Search command palette
Alternatively, you could go to File > Preferences > User Snippets.

You can now create a .json file full of snippets.
You can either create a language specific file, for example:
javascript.json
Snippets defined here will only apply on a javascript document.
Or you can define a global snippet file. The global ones should end with the .code-snippets extension, for example:
my-global-snippets.json.code-snippets.
Since I am learning react, I created a file named
javascriptreact.json
Snippets here will be available in all .jsx file.

Writing the Snippet

To write the snippet you have to give it a name and associate it with an "object" (it is a JSON, after all), like this:

{
  "Snippet Name" : {
    // keys and values here
  }
}
Enter fullscreen mode Exit fullscreen mode

The more important keys are:

  • prefix: The shortcut that will invoke it (could have many)
  • body: The code created when invoked
  • scope: If you created a global snippets file, you can pass languages here, so that it will only be available for those languages. You can ignore this if you created a language specific file
  • description: You can pass some text that will show up on autocomplete with information about the snippet here. If no description is passed, it will use the snippet's name.

Here is an example that I'm using:

"React Function Component Export" : {
  "prefix" : "fc",
  "body" : [
    "import React from 'react';",
    "",
    "function ${0:$TM_FILENAME_BASE} () {",
    "\treturn (",
    "\t\t<div>",
    "\t\t\t",
    "\t\t</div>",
    "\t);",
    "}",
    "",
    "export default ${0:$TM_FILENAME_BASE};",
    ""
  ]
},
Enter fullscreen mode Exit fullscreen mode

Note that \t is a single tabulation. Also, \n would have worked for new lines and so on

The prefix here is set to fc, so every time I'm inside a .jsx file, writing "fc" and hitting TAB will generate this code. Now that's useful!

It is also worth noting that CTRL + SPACE will also show the "suggestions" of a particular word, including the snippets

You could also pass many prefixes, like this:
"prefix": ["fc", "rfc", "funcomp", "hello"]
Also, the body supports many special characters. In this example:

  • $0: This is a "tab-stop" and will put the cursor in this position when the snippet is invoked. Passing repeated tab-stops will give you multiple cursors right from start! You could also have more than one tab-stop without using multi-cursors, just use different indexes for them: $0, $1 etc. It is possible to cicle through those different indexed tab-stops after the snippet was invoked with the TAB key
  • ${0:text}: This is a tab-stop that has a initial value of "text"
  • $TM_FILE_NAME_BASE: This is a variable that will have the name of the file where the snippet was invoked but without it's extension. There are multiple available variables that you can use

We can look for all the available variables and everything else about writing our own snippets at the documentations:
https://code.visualstudio.com/docs/editor/userdefinedsnippets

Project Specific Snippets

Upon creation, you could also specify a snippet to a project, so that it will not be available anywhere else.
Imagine that for a specific project you have to write some particular text/code very often. Maybe some import, or have some kind of class template, who knows.
In those cases it is probably a good ideia to create a project specific snippet.

To do that, you can either open the Command Pallet, search for snippets and choose the New snippet file for [PROJECT NAME] option. It will create a /.vscode folder at the root of the project's directory and put the json there.
You can now determine the:

  • scope (languages)
  • prefix (shortcut to invoke) and
  • body (actual code)

of all the necessary snippets in that file.

VSCode Extensions, again...

Now, don't get me wrong. I know that people work hard and put a lot of love and effort in creating extensions that come with a number of very nice snippets, and I'm not against this. I'm just saying that, specifically when learning a new technology, it is probably a bad idea. You can use one of those extensions to fill the more generic and everyday snippets and customize just a few particular ones, if you want.

And finally...

Have fun!

Customizing your workspace is fun and helps not only at being productive but also at learning better how things work. I hope I helped someone out there with customizing it's own snippets, because that is something that I'm finding particularly useful.
Thanks for reading, and don't forget to check the docs!
https://code.visualstudio.com/docs/editor/userdefinedsnippets

Stay safe 😊

Top comments (2)

Collapse
 
mstrblonde profile image
Christian McFadden

Snippet Generator is a super-handy tool: snippet-generator.app/

Collapse
 
lucassperez profile image
Lucas Perez

Indeed, that looks great! Thank you 😁