Visual Studio Code Snippets

VS Code offers the possibility to create personalized code snippets. These Code snippets can be configured for a specific user, globally, for a certain project or programming language. 

For example, if a user wants to avoid the repetitive writing of the basic "console.log({})", after configuring the snippets, it will be enough to write a prefix like: "cl" or "log" and VSC will autocomplete the code snippet. The braces `{}` will also show the variable name before the result.

In order to achieve this, we can run the command "Preferences: Configure User Snippets" in VSC and a popup will appear showing the types of of snippets to configure.

If we wish to configure a snippet as in the 'console.log' example above, we need to choose to modify the "javascript.json" file with the following content: 

```
{
    "Print to console": {
        "prefix": "cl",
        "body": [
	    "console.log({$1});",
	    "$2"
	],
        "description": "Log output to console"
	}
}
```

As you can see, a certain snippet will have a prefix under it will be accessed, a body (the code that will be inserted) and the description of the snippet.

This is a powerful feature of VSC and can avoid repetitive code writing that can be quite tedious after a while.

More info about this feature of VSC can be found here: 

 https://code.visualstudio.com/docs/editor/userdefinedsnippets#_create-your-own-snippets

Mihai Barbu
06 Dec 2021
« Back to post