DEV Community

Cover image for Faster development with code snippets in Visual Studio Code
Mateus Morais
Mateus Morais

Posted on

Faster development with code snippets in Visual Studio Code

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.

I am currently working in a React 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 so my components basically starts with:

// MyComponent.tsx
interface MyComponentProps {}
export function MyComponent(props: MyComponentProps) {
  return (
    // ... JSX Code here
  );
}
Enter fullscreen mode Exit fullscreen mode

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

If you click the option foreach:

snippet foreach

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:

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

myArray.forEach(item => {
  // code goes here
});
Enter fullscreen mode Exit fullscreen mode

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

add global snippet

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:

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

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

Selecting log will show the following:

console log

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
Enter fullscreen mode Exit fullscreen mode

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:

{
  "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"
  }
}
Enter fullscreen mode Exit fullscreen mode

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:

{
  "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"
  }
}
Enter fullscreen mode Exit fullscreen mode

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

selecting react snippet

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.

Top comments (0)