photo of clouds and lightning
Photo by Felix Mittermeier on Unsplash

Automating Your Workflow With Code Snippets

Find out how using code snippets can help you speed up common tasks.

6 min read

Recall the last time you needed to write the same code several times, maybe over the course of the day, or even an hour. It could have been scaffolding out a React component, a unit test, or something more specific to your project, like a blog Markdown file template. Did you write it from scratch each time? Hopefully not! If you did, this post can help add some precious minutes back to your day. We'll cover what code snippets are, why they are useful, and how to make your own using some examples.

While this post will focus on Visual Studio Code, the overall idea can be applied in almost any text editor or IDE.

What Is a Code Snippet?

Code snippets are not a new concept, and for many of us they are an indispensable part of our workflow. But for those not familiar, a code snippet is just as it sounds: a snippet of code.

Whatever this snippet is, it can be recalled and used whenever you need it by typing a predefined trigger word or character(s). The beauty is that if you write your own snippet, you determine what the trigger is!

The ability to add and use code snippets has been a feature in most modern IDE's and text editors for a very long time. The thing is, they are often overlooked and underused. They can be "just another thing to remember", and some of the terse syntax required for them can be hard to recall without practice. But...

Code Snippets Are Very Useful

The things you can do with code snippets are only limited to your own imagination and are very much worth the time they might take to memorize.

The best reasons to use them are:

  1. Saving time - It might sound insignificant, but the amount of seconds or even minutes spent writing a Redux reducer, scaffolding a React component, or manually typing HTML can really add up!
  2. Enforcing consistency - Code consistency is very important, and any way to create a template that contains your ideal code style should be utilized.
  3. Automating boilerplate - Related to #1 above: As developers, our time is better spent not writing the same thing over and over every time we need it. Instead, let your editor do the tedious work for you just by typing a few characters and hitting enter.
  4. Eliminating guesswork - For code syntax that's hard to remember, having a snippet handy will save you from needing to search for it.
  5. Project-specific Tasks - Code snippets are great for tasks that are specific to your codebase. For example, if your project is a blog that uses markdown, you could have a snippet for creating a front matter template that contains common metadata that you always use.

Why not just copy and paste from something you did before, or use a CLI tool to generate a file for you? I realize these are options too, but they're not always good options.

If you're in the middle of working in a file you've already created, a CLI tool probably won't help. If you have a small piece of code you have written before, why hunt it down from some other file, only to hack out most of the parts that don't apply to what you're currently writing? Instead, create a snippet containing the skeleton of the code you need, type a few characters, and have your editor do the work.


Prebuilt Snippets

First, let's cover some prebuilt code snippets that are installed as VS Code extensions. A few of the ones I use are:

Some of these examples are React-specific, but there are snippets available for Vue, Laravel, and many other languages.

Let's assume you want to write a new React component. If you have the Reactjs Code Snippets extension installed, all you need to do is type rscp to get the code suggestion box to appear.

rscp code snippet example


Hit "enter," and the snippet will output an entire component skeleton.


import React from 'react';
import PropTypes from 'prop-types';

const MyComponent = props => {
  return (
    <div>

    </div>
  );
};

MyComponent.propTypes = {

};

export default MyComponent;

As you can see, this is a real time saver and you only have to type four characters!
Not only that, but it helps enforce code consistency (#2 from the list above) around what a preferred React component should look like in your codebase.

Writing Custom Snippets

The more you use code snippets, you'll start to encounter scenarios where having one available would be helpful, but your use case is specific to your project and it doesn't already exist. Fortunately, writing your own VS Code snippets is pretty straightforward.

In VS Code, open up the Command Palette and type snippets until you see the option "Configure User Snippets".

vs code user snippet configuration
vs code user snippet configuration


When you click this, you'll notice several different types of snippets that available, and it will usually depend on what language you're writing in. For a basic example to start with, let's create a javascript code snippet by clicking javascript.json.

This .json file is where all of your JS-specific snippets will live.

If you enter a snippet into a language specific .json file, it can only be used with filetypes of that language. If you want snippets that can be used with various different filetypes, just choose "New Global Snippets File" or "New Snippets File for your_project_name".

Once you have the file open, there should be an example snippet commented out, as well as a basic description of how it works.

The overall format looks like this:


"Snippet name": {
  "prefix": ["some", "trigger", "chars"],
  "body": [
    "snippet code here",
  ],
  "description": "Snippet description"
},

Console.log Example

Using the format from above, let's add a snippet that outputs console.log().


"Console.log": {
  "prefix": ["cl", "cons"],
  "body": [
    "console.log($0);",
  ],
  "description": "Add Console.log()"
},

As the "prefix", we have an array of strings so that if you type either "cl" or "cons", both will make the snippet available.

Within the body, we have the console.log() that we want to output, as well as a $0 value. This is what is called a "tabstop", and is a way to control the tab order once the snippet is output. In this case, we want our cursor to initially appear inside the parenthesis, because we obviously want to log something. You can use as many tabstops as you want, and they should descend down to 0, decrementing for each time the tab key is hit.

To test this out, type "cl" or "cons" into a .js file in your codebase.

console log snippet output
console log snippet output


If all went well, you have a simple console.log() output with the cursor ready to type whatever you want to log.

CSS Media Query Example

For another example, let's look at creating a snippet that outputs a min-width media query in CSS. As before, we'll want to access the Command Palette, and this time select CSS (or SCSS/LESS) from the list to open the corresponding .json file.
The snippet we create should look like this.


"Media query": {
  "prefix": ["mq-min", "min"],
  "body": [
    "@media screen and (min-width: ${1:value}) {",
    "\t$0",
    "}"
  ],
"description": "Adds a min-width media query"
}

For the prefix, we want "mq-min" or even just "min" to trigger the snippet.

Within the body, we are using a placeholder ${1:value}, which is just a tabstop that contains some placeholder text. Here we want to make it obvious that min width needs a value and the cursor will appear here first once the snippet is output.

The next line has the final tabstop, with a \t in front of it to format a tab, and the final line just has the closing brace.

When this file is saved, go to any CSS file and try it out by typing "min" or "mq-min".

media query snippet output
media query snippet output


There are a lot of options and customizations for code snippets that I didn't cover here. You can check out the VS Code documentation for more info.

Summary

I hope this post inspires you to start using code snippets in your daily workflow, and if you already do, to think about any you could be missing! The hardest part about starting to use code snippets is just remembering what the trigger words or characters are, but once you memorize them, they will become second nature and save you time.