Faster development with code snippets in Visual Studio Code
Tags: vscode, productivity, webdev, codenewbie
Published: 2021-07-21 12:44:21

Technology is advancing and with it the power of the tools we use advances too. We often see tools getting more easier to use and full of new functionalities that helps us in our daily routine. One of the tools I like to use when I’m writing code is [Visual Studio Code](https://code.visualstudio.com/).

I am currently working in a [React](https://reactjs.org/) project and, if you are familiar with the framework, you know that when writing a component or page from scratch there is a basic “boilerplate” you may usually follow.

For example, in my current project I’m using [Typescript](https://www.typescriptlang.org/) so my components basically starts with:

```ts
// MyComponent.tsx
interface MyComponentProps {}
export function MyComponent(props: MyComponentProps) {
  return (
    // ... JSX Code here
  );
}
```

If you work with React, my guess is that your components also look something like this, or even if they don’t, their basic structure shares some similar lines of code. Looking at my example you may notice that I repeated the word `MyComponent` 4 times.

In this article I will show you how to create code snippets that will help you while coding.

## Code snippets on VSCode

Code snippets are a way of saving time when creating basic known structures of code. They are templates that make it easier to enter repeating code patterns. You may not have noticed, but if you need to iterate an array using `forEach` and you start typing “for” on a `.js` file, VSCode suggests:

![slecting existing snippet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j66bere2d92l2s00bi5v.png)

If you click the option `foreach`:

![snippet foreach](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n2bef6sv2dyah9uqxlzy.png)

VSCode places your cursor on the `array` field, so you can type the name of the array variable you want to iterate through. When you press `Tab` the cursor moves to the next position, which is `element`. You can then define the name of the item reference in each iteration. Press `Tab` again, and you end up in the body of the function.

After filling the placeholders, you end up with something like this:

```ts
const myArray = [1, 2, 3, 4, 5];

myArray.forEach(item => {
  // code goes here
});
```

Pretty neat, huh?

The inevitable question we ask ourselves now: “is there a way to create my own snippet?” And the answer is yes! VSCode provides us a way of creating user snippets that will be triggered by typing part of a keyword, the same way we triggered the `foreach` snippet by typing “for”.

## Creating your first code snippet

To create your code snippet you need to go to “File > Preferences > User Snippets”. This will open a drop-down menu in which you should click “New Global Snippets file…”. You can also create snippets for a specific project in your workspace.

![creating snippet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r8bv51ewqo9cwoy0j14i.png)

![add global snippet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kktqjqab83azyuh1og4f.png)

When you create your custom snippets they will show up before the button to create a new snippet.
After you are prompted to give a name to the snippet you will create you should see a template with multiple commented lines. We will begin based on this example, give by VSCode itself:

```json
// new-component-react.code-snippets
{
  "Print to console": {
    "scope": "javascript, typescript",
    "prefix": "log",
    "body": [
      "console.log('$1');",
      "$2"
    ],
    "description": "Log output to console"
  }
}
```

If we save the snippet and start typing the prefix `log` in a `.js` or `.ts` file, you can see the snippet shows up as a suggestion:

![log snnippet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/srvtz0imi370t2hgcmd1.png)

Selecting `log` will show the following:

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

### Understanding each field on the snippet

As you may have noticed, the first and only key of the snippet “Print to console” is the title of the snippet and the field `description` is a more detailed description that shows on the side of the option. The `prefix` field is what keyword is going to be used to find the snippet in the auto suggestion sub menu. The `scope` defines in what file types typing the snippet will show on auto suggestion (in this first example, `.js` or `.ts` files).

The `body` field is the template code that will be provided for you to complete. It’s an array where each line in the array is a line on the file. To create the body of our snippet, we need to understand how to add placeholders.

### Adding placeholders

Placeholders in a VSCode snippet are identified by the `$` sign. The number after it is the `Tab` order. You can also provide a default text if you like. For example, in the `foreach` snippet the first placeholder has a default text of `array` and the second has `element` as default text. This can be achieved by placing the default text after the placeholder and enclosing it with curly braces, like this:

```
{$0:array} // will be a placeholder with 'array' as default text
{$1:element} // will be a placeholder with 'element' as default text
```

## Creating our react component snippet

Let’s go ahead and create our component snippet. I will call it `react-component-ts`. Here is the snippet:

```json
{
  "React component with typescript": {
    "scope": "typescriptreact",
    "prefix": "react-component-ts",
    "body": [
      "interface $1Props {}\n",
      "export function $1(props: $1Props) {",
      "\treturn ($2);",
      "}\n",
    "description": "Basic react component with typescript"
  }
}
```

Our scope here is `typescriptreact` which basically is the way of telling VSCode that the file format where the snippet may be available is `.tsx`.

Notice that by using the same placeholder `$1` on multiple places, when we use the snippet and start typing the name of the component, we will also have the name of the interface and props type already written. After that, if we press `Tab`, the cursor goes inside the return parenthesis and you can start coding your component!

### If you are a lazier

If your component’s filename is also the name of the component, there is another trick you can use, which is a variable placeholder. The placeholder `$TM_FILENAME_BASE` returns the filename to be used in the snippet. So, the final version would look like this:

```json
{
  "React component with typescript": {
    "scope": "typescriptreact",
    "prefix": "react-component-ts",
    "body": [
      "interface ${TM_FILENAME_BASE}Props {}\n",
      "export function $TM_FILENAME_BASE(props: ${TM_FILENAME_BASE}Props) {",
      "\treturn ($1);",
      "}\n",
    "description": "Basic react component with typescript"
  }
}
```

> To name the interface we have to use the placeholder in a slightly different way (`${TM_FILENAME_BASE}`), so VSCode understands that the variable name is `TM_FILENAME_BASE` and not `TM_FILEBASE_NAMEProps` (which wouldn’t work).

Now, all you have to do is create a `.tsx` component and inside it search for the preffix:

![selecting snippet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s4rm1ggx926mf465d76w.jpg)

![selecting react snippet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cgeb8es42le31oq1p7ff.png)

And you are ready to code!

## Conclusion

In this article we were able to see how code snippets work in VSCode. We also were able to create our very own code snippet to a React component. The problem we solved here is one I had in real life, and felt like sharing. I honestly hope you can see the power this could bring to your development routine.

If you would like to read and learn more about user snippets, you can check the docs here. There you may find a bunch of other tools to write your snippet in order to meet your needs. There are also extensions in VSCode you can add that provides multiple snippets, framework based or language based.