How to create custom VS Code snippets?
Tags: vscode, webdev, productivity, tooling
Published: 2022-11-17 19:57:16

If you are a developer and use Visual Studio Code daily, you must have experienced the same problem.

How can you create custom VS Code snippets and double your coding productivity?

This blog post will teach you everything you need to know about creating your own snippets inside Visual Studio Code.

## Benefits of using Snippets:

There are several benefits, but here is the list of the most important ones:


- It enhances readability by breaking it into smaller chunks.
- It adds more reusability by allowing you to reuse the same code in multiple places.
- It increases reliability by avoiding errors when copying and pasting.
- Minimize time spent writing code.
- Increase the speed of your development.


## Types of Code Snippets in VS Code:

Snippets are scoped. There are three types:

1. Language Specific (Only specific language can access).
2. Global Snippets (Every language can access).
3. Project Scoped (Restricted to project).


## Access Snippets Manager:

There are two simple ways to access the user snippets manager:

1. First, click on the settings icon at the bottom left of VS code.
2. Type ctrl + shift + p and then type snippet.


![configure user snippets through bottom VS Code settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vmju2cy9ymbt5iczzqmv.png)

**You can do the following:**

1. Search for specific code
2. Configure User (Custom code blocks)
3. Insert (Built-in Snippets)
4. Populate file

![four defaults of snippets in vs code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sazv4vj0m8973sqxs4ye.png)



## VS Code Snippet Syntax:

When you click on Configure User, it will ask you to name the snippet file.

After that, you will see an object containing instructions to create a snippet.


**Basic Syntax:**

- Each new snippet is a JSON object.
- It will have a snippet name, scope, body, prefix, and description.
- Define the scope of programming languages using commas to separate them or leave the field empty for all languages.
- A prefix is a short form to access the piece of code.
- Handle tabs using tab stops like $1, $2, $3, and so on.
- Use placeholders to set default values.
- A description field is useful for intellisense.

**Default Example:** Print to Console

![default snippet object with instructions](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bd3d7070k7v9m4vgsuye.png)


![print to console sample example code snippet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/we3k95djp0qoians9528.png)

### **Tab stops:**

When you press the Tab key, the cursor moves from one point of the snippet to another. That is where tab stops are helpful.

$ dollar sign represents the order of the tab stops, like $1 represents the first place, $2 represents the second place, and so on.

**Example:**

![console log two elements - example of tabstops](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/joot98uao0rp1s6lf5jg.png)

### **Placeholders:**

A placeholder is a value that is put into a code template and later replaced with actual values.

You can use ${1:placeholderValue} i.e ${1:replace me}

**Example:**


![vs code snippets placeholders](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o50jj7b78cik0awbrza1.png)

### **Choice:**

Just like placeholders, you can use choices. It's like giving the user an option to select from the dropdown.

All choices are between the pipes and with comma-separated values.

You can use something like : ${1|value1,value2,value3|}

**Example:**

![console log with default choices](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/anoqpxtxq003f29v96zv.png)


### **Default Variables:**

There are several pre-defined [variables in Visual studio code](https://code.visualstudio.com/docs/editor/userdefinedsnippets#_variables):

- TM_FILENAME: Name of the current file.
- TM_DIRECTORY: Directory of the current document.
- CLIPBOARD: Contents of your clipboard.
- And much more.

You can use something like ${CLIPBOARD:backupValue}. If the value of a variable doesn't work, then the backup value will print.

**Example:**

![example of default variables](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/agdkp2xhrvy5gw737lon.png)



## Create and Use Basic Custom Snippets:

Let's create some JavaScript snippets.

**Case:**

Create a piece of reusable code that should allow you to select DOM elements using core methods like:

- getElementById
- querySelector
- querySelectorAll
- getElementsByTagName

**Example:**


![get document elements JS snippet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ohwfog1csikfntedrfcs.png)

![select document elements with core methods](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58odgu3jlage9osg900r.png)

## Smarter Way to Create custom Code Snippets in VS:

Now that you have learned enough about the manual creation of snippets.

Let me introduce you to the benefits of [Codiga VS Extension](https://www.codiga.io/get-codiga/vscode/).

- Easy installation and configurations.
- A super effective way to share code with a group of people.
- You can access snippets anytime from the cloud.
- Access to Codiga Coding Assistant (Easily search for useful code samples).
- Connect your VS directly to Codiga to store any useful snippet.
- Use your stored snippet instantly.

### Codiga can change your snippets flow super easily:

VS Code extension is super powerful and contains multiple features which can boost your coding productivity to the next level.

It has a built-in coding assistant, a snippets manager, inline shortcuts, a code cheat sheets panel, and a code search engine.

Let's see how the Codiga VS Code extension works.


**Step 1:**

Just go and install [Codiga Extension](https://marketplace.visualstudio.com/items?itemName=codiga.vscode-plugin) in your IDE. 

Alternatively, you can search (Codiga) inside VS Code extension manager.

![codiga extension inside vs code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n95b72tj0hwh5aeyyy1p.png)

**Step 2:**

Now, write your code snippet. In my case, I just wrote an example of IIFE in JavaScript. 


![iife javascript code sample](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cz2tq6etj0dd9a3otvro.png)


**Step 3:**

Select your snippet, press right-click, and go to **Create Codiga Snippet**.

**Note:** Once you click, it will ask you for an API key. Since Codiga stores snippets on Cloud, you can access them anywhere, so you need a free Codiga account. 


**Step 4:**

Go [here](https://app.codiga.io/api-tokens) and create your API Token.

**Note:** If you don't have an account, create your account with any of the options (GitHub, Gitlab, BitBucket, Google). 


![create token inside codiga](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h3u22mf02b3fwqolw295.png)

You can name it anything. So I named it **My Personal PC** and hit **Create Token**.


![name codiga token api](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o8ibfq41bnl1sea4ivzk.png)

**Step 5:**

Copy your token and get back to the code editor. Go to the VS code settings (**CTRL +,**) or (**⌘ +,**). Search for Codiga.

Place your copied API token inside the input.


![place codiga api token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yglsef2d514r5gaydx6p.png)

**Step 6:**

Now, select your snippet, right click and try to **Create Codiga Snippet**. This time, it should redirect you to the Codiga dashboard, where you can save the code block.

![codiga snippets manager dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dpne7kbshovaywlmx6km.png)

**Step 7:**

Put name, select programming language, library, imports, and snippet privacy (Private or Public).

**Note:** I named my snippet "**Create IIFE boiler**"

![create codiga snippet details](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jywr76ztdnhsujvdaw5d.png)


**Step 8:**
If you successfully saved your code snippet, it's time to use it inside VS Code. 

**Note:** You can also use other useful snippets publicly available or from the **Codiga library**. 

For example, this flattened array code doesn't exist in my snippets collection, but still, it showed me the code.


![flatten array-sample code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ovebyxt02zgsr4xlgfi8.png)


You can **access snippets in several ways**:
- Type in Comments 
- Using Inline Shortcuts 
- From Codiga Code Cheatsheet Panel
- Internal Codiga Search engine (CTRL + ALT + C)

**Type in Comments:**

**Note:** Some programming languages directly use # hashtag for comments. But, in our case (JavaScript), we will use two forward slashes and then a hashtag.

![type in comments](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/74wor997gg22lgfc2h33.png)

**Using Shortcuts is super simple:**

Open the snippet in the Codiga dashboard, and click on edit (pencil icon). 

You will see optional tabs (metadata and groups). 

Click on metadata and assign a shortcut to your snippet.


![codiga shortcuts dashbaord](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xkr7kvq3pkpvq7mg6830.png)

You can call shortcuts by using (. or /) or (**CTRL + ALT + S**) to quickly access the code block.

(**CTRL + ALT + S**) Which opens the code cheat sheet panel.

![Codiga cheat sheet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qgkbb5c9mp3epzje2zuh.png)

(. or /) is used to insert **inline snippets**.



![inline codiga snipet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/shi08qz0rf9fhas5y1pu.png)



## Conclusion:

That concludes our session for today. If you have not already created a few snippets, I recommend doing so.

It is an excellent way to increase your development process.

As you become more accustomed to creating custom code shortcuts, you will find it easier to save time and improve your coding productivity.

And If you're looking for a better way to create and manage your snippets, check out our new [code snippets manager](https://www.codiga.io/code-snippets/code-snippets-manager/).


## FAQs:

### What are snippets in VS Code?

Snippets are a collection of commonly used code or templates that can be inserted and reused in a document by pressing a defined shortcut key or phrase. In VS Code, you can easily create, modify and include snippets by configuring them through the code blocks manager.

### Are there any pre-built VS snippets?

Yes. Type ctrl+shift+P (or cmd+shift+P on mac) to open the Quick Open dialog, then type 'Insert snippet' to see a list of available snippets.

### How to insert a snippet?

You can call the prefix which you created during the creation of your code block.

### Where are VS code snippets stored?

It stores global snippets in the user's home directory.

And if you want project-level snippets, create a .vscode folder; inside that, you can manage project snippet files with the .code-snippets extension.