This article will show you how to create code snippets in VS Code
User Case
Code snippet can improve your coding productivity with frequent used code or code structure, for example, print an object structure and data in console when you want to check detail information of that object in typescript language. I’ll create a code snippet for this in VS Code.
Prepare a snippet file
Open VS Code, go to Preferences > Create User Snippets, then choose either “New global snippets file…” or configure existing snippets file, in this case, I’m going to create a new global snippets file called my-snippet.json, click “Enter” then you’ll have a snippet file created, below is an example to print an object as JSON format.
{
// Place your global snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and
// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope
// is left empty or omitted, the snippet gets applied to all languages. The prefix is what is
// used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $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.
// Example:
"Print to console": {
"scope": "javascript,typescript",
"prefix": "log",
"body": [
"console.log(JSON.stringify('$1', undefined, 4));",
"$2"
],
"description": "Log output to console"
}
}
Save the file and your global code snippets is ready to go.
Test it out
Type ‘log’ in a typescript file or javascript file, you’ll have a code suggestion something like below, use arrow key to choose the one you want to use in your file, click enter and voila, you’ll have a line of print log code inserted
console.log(JSON.stringify('', undefined, 4));