Guide to Custom VS Code Snippets and Why You Need Them
Tags: productivity, vscode, programming
Published: 2020-11-19 09:50:10

# Introduction

## The problem

I've been coding for quite a while now and one thing I've noticed is that I use the same code a lot. Whether it be a function using CURL to fetch url contents, CSS properties to apply material box-shadows, or simply create EventListeners in JavaScript. Usually this means I end up wasting time doing it again, or in some cases I look through my old projects to copy-paste the code I've written. I've come up with a few solutions to this problem such as using GitHub Gists, but VS Code Snippets is by far the best.

## The solution

Visual Studio Code and Emmet let you make snippets that write large blocks of code with tiny shortcuts. You can access entire functions you've written with just a couple key presses.

## Overview

In this tutorial, I will show you how to create custom code snippets for HTML and CSS using Emmet and also for **all types** of languages and files using VS Code User Snippets. You can create abbreviations for code in all of your favorite languages including JavaScript, React, PHP, Python, Markdown, and others.

You will learn how to create custom Emmet Abbreviations to type HTML structures and CSS properties faster, boilerplates for your favorite languages, function snippets with labeled and unlabeled tabstops, and how to use VS Code's variables in your snippets.

## Video tutorial

{% youtube gU7b5Vgnalw %}

# Part 1: Custom Emmet Abbreviations

If you don't yet know, Emmet is an amazing tool that is built into VS Code that allows you to type complex HTML structures quickly and type CSS properties with abbreviations. You can learn more about it [here](https://youtu.be/5ecM9n7A_pY).

Now that you know about Emmet Abbreviations, here's how you can create your own abbreviations for HTML structures and CSS properties!

## Create a snippets file

Find a place on your computer to store your snippets. I chose `C:/Users/jonah/emmet/`, but you can pick any folder you like.

Create a new JSON file and call it `snippets.json`.

## Add the path to your settings

Open your user settings. You can do this by pressing `F1` and searching for the command `Preferences: Open Settings (JSON)`.

Add the `emmet.extensionsPath`

For me, this looks like:

```json
{
   ...
   "emmet.extensionsPath": "C:\\Users\\jonah\\emmet",
}
```

## Add your snippets

Use this template in your `snippets.json` to add abbreviations.

```json
{
  "html": {
    "snippets": {
      // html snippets here
    }
  },
  "css": {
    "snippets": {
      // css snippets here
    }
  }
}
```

Here's an example of snippets I have set up:

Symbols such as `{$1}` are tabstops and `${1:1px}` is an example of a tabstop with a default value.

Watch how these work in [the video](https://www.youtube.com/watch?v=gU7b5Vgnalw).

```json
{
  "html": {
    "snippets": {
      "ull": "ul>li.item${${1:Item $}}*3",
      "hsf": "header+section+footer",
      "gfont": "link[rel=preconnect][href=\"https://fonts.gstatic.com\"]+link[href=\"https://fonts.googleapis.com/css2?family=${1:Open+Sans}&display=swap\"]",
      "lbi": "label>input[class]",
      "lbc": "label>input:c[class]+{$1}"
    }
  },
  "css": {
    "snippets": {
      "bn": "border: none",
      "on": "outline: none",
      "bsd": "border: ${1:1px} solid ${2:red}",
      "cw": "color: white",
      "cb": "color: black",
      "tra": "transition: ${1:all} ${2:0.3s} ${3:cubic-bezier(0.25, 0.8, 0.25, 1)}",
      "teo": "transition: ${1:all} ${2:0.2s} ease-out",
      "tei": "transition: ${1:all} ${2:0.2s} ease-in",
      "fww": "flex-wrap: wrap",
      "cp": "cursor: pointer",
      "tt": "transform: translate(${1:0px}, ${2:0px})",
      "ttx": "transform: translateX(${1:0px})",
      "tty": "transform: translateY(${1:0px})",
      "tr": "transform: rotate(${1:90deg})",
      "pen": "pointer-events: none",
      "fdc": "flex-direction: column",
      "fdcr": "flex-direction: column-reverse",
      "fdr": "flex-direction: row",
      "fdrr": "flex-direction: row-reverse"
    }
  }
}
```

# Part 2: Custom VS Code User Snippets

Select User Snippets under `File > Preferences` (`Code > Preferences` on macOS).

Select the language you want to create snippets for or select "New Global Snippets file" to create snippets for all languages.

Each snippet is defined under a snippet name and has a prefix, body and description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. 

Placeholders: $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the same ids are connected.

Here is an example of my `javascript.json` snippets file:

```json
// javascript.json

{
	"Document Query Selector": {
		"prefix": "dqs",
		"body": [
			"document.querySelector(\"$1\")"
		]
	},
	"Document Query Selector All": {
		"prefix": "dqsa",
		"body": [
			"document.querySelectorAll(\"$1\")"
		]
	},
	"Add Event Listener": {
		"prefix": "ael",
		"body": [
			"addEventListener(${1:\"click\"}, $2 , false);"
		]
	},
	"Add Event Listener Function": {
		"prefix": "aelf",
		"body": [
			"addEventListener(${1:\"click\"}, function () {",
			"\t$2",
			"} , false);"
		]
	},
}
```

You can also use snippets for boilerplates or awesome CSS shadows:

```json
// css.json

{
	"CSS Boilerplate": {
		"prefix": "!",
		"body": [
			"html {",
			"\t-webkit-box-sizing: border-box;",
			"\t-moz-box-sizing: border-box;",
			"\tbox-sizing: border-box;",
			"}",
			"",
			"*,",
			"*:before,",
			"*:after {",
			"\t-webkit-box-sizing: inherit;",
			"\t-moz-box-sizing: inherit;",
			"\tbox-sizing: inherit;",
			"}",
		]
	},
	"Shadow Depth 1": {
		"prefix": "shadow1",
		"body": [
			"box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);"
		]
	},
	"Shadow Depth 2": {
		"prefix": "shadow2",
		"body": [
			"box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);"
		]
	},
	"Shadow Depth 3": {
		"prefix": "shadow3",
		"body": [
			"box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);"
		]
	},
	"Shadow Depth 4": {
		"prefix": "shadow4",
		"body": [
			"box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);"
		]
	},
	"Shadow Depth 5": {
		"prefix": "shadow5",
		"body": [
			"box-shadow: 0 19px 38px rgba(0, 0, 0, 0.30), 0 15px 12px rgba(0, 0, 0, 0.22);"
		]
	}
}
```

## Variables

VS Code also has variables you can use in your snippets.

* `TM_SELECTED_TEXT` - Currently selected text
* `TM_CURRENT_LINE` - Current line contents
* `TM_CURRENT_WORD` - Word under the cursor
* `TM_LINE_INDEX` - Zero-index based line number
* `TM_LINE_NUMBER` - One-index based line number
* `TM_FILENAME` - Filename of the current document
* `TM_FILENAME_BASE` - Filename without extensions
* `TM_DIRECTORY` - Directory of the current document
* `TM_FILEPATH` - Full file path of the current document
* `CLIPBOARD` - The contents of your clipboard
* `WORKSPACE_NAME` - The name of the opened workspace or folder

* `CURRENT_YEAR` - Current year
* `CURRENT_YEAR_SHORT` - Last two digits of current year
* `CURRENT_MONTH` - Month as two digits (ex. '03')
* `CURRENT_MONTH_NAME` - Full name of the month (ex. 'March')
* `CURRENT_MONTH_NAME_SHORT` - 3-letter abbreviated month name (ex. 'Mar')
* `CURRENT_DATE` - Day of the month
* `CURRENT_DAY_NAME` - Name of day (example 'Monday')
* `CURRENT_DAY_NAME_SHORT` - Short name of the day (example 'Mon')
* `CURRENT_HOUR` - Current hour in 24-hour clock format
* `CURRENT_MINUTE` - Current minute
* `CURRENT_SECOND` - Current second
* `CURRENT_SECONDS_UNIX` - Number of seconds since the Unix epoch

* `BLOCK_COMMENT_START` - Example: `<!--` in HTML, `/*` in JavaScript, PHP, etc.
* `BLOCK_COMMENT_END` - Example: `-->` in HTML, `*/` in JavaScript, PHP, etc.
* `LINE_COMMENT` - Example: `//` in JavaScript, PHP, etc.

## Block comment example:

The following in `global.code-snippets` will insert a block comment in any language. It will insert `<!-- | -->` in HTML and `/* | */` in JavaScript, PHP, etc. when you type `cc`. The `$1` will place the cursor in the center when you press tab.

```json
{
	"Block Comment": {
		"prefix": "cc",
		"body": [
			"$BLOCK_COMMENT_START $1 $BLOCK_COMMENT_END"
		]
	}
}
```

## Date and time example:

The following in will insert the current date as YYYY-MM-DD. You can write the date in many different formats using a combination of variables from above.

```json
{
	"Date": {
		"prefix": "date",
		"body": [
			"$CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE"
		]
	}
}
```

# Conclusion

Code snippets are a great way to type code faster and more productively. There is a great feeling to be able to access the code you want in less than a second. No more need to search through your old files to get the things you need!

I hope you learned something!

If you want to learn more coding tricks, subscribe to [my channel](https://www.youtube.com/channel/UCipSxT7a3rn81vGLw9lqRkg)!

Thanks for reading / watching!