Using code snippets in Visual Studio Code (VS Code) can be a major time saver. Snippets allow you to insert blocks of pre-defined code, triggered by typing a short pattern. These can seriously cut down the monotony of typing the same boilerplate code over and over, while avoiding syntax errors. They can even help your team enforce a consistent code style. Here’s a guide on how to create your own custom code snippets.
Built-in Snippets and Extensions
Before we get started, it’s worth mentioning that VS Code comes with a variety of built-in snippets for most popular languages. To access these, just start typing a common code pattern (such as “for”, “if”, or “try” in JavaScript), and VS Code will suggest relevant snippets. Additionally, VS Code’s marketplace offers numerous extensions that add language-specific snippets, like ES7 React Snippets or Python Snippets. Installing these can cover a broader range of use cases for your favorite frameworks or libraries.
Creating Custom Snippets
While built-in snippets can helpful, many times they don’t align with your code style, or even support the patterns you need most. The true beauty of code snippets is in being able to create your own.
Here’s how to create custom snippets:
- Create a
.code-snippets
file in your projects.vscode
directory. To do this with settings shortcut, press “Cmd + Shift + P”, search “Snippets”, and choose “Snippets: Configure Snippets” -> “New Global Snippets file”. You’ll be prompted to enter a file name, and then a new snippets file will be created for you. - In the JSON file that opens, you can define a snippet using this simple format:
{
"Your Snippet Name": {
"prefix": "trigger",
"body": ["Your snippet code goes here"],
"description": "Describe your snippet's purpose here"
}
}
- The
prefix
is the keyword you type to trigger the snippet, and thebody
is the code it inserts. For multiline snippets, simply add each line as a separate string in thebody
array.
Placing The Cursor with Tabstops
You can use tabstops in your snippets to place your cursor automatically. Here’s a quick one for an easy console log:
{
"Console Log": {
"prefix": "clg",
"body": ["console.log('$1');"],
"description": "Log output to the console"
}
}
In this example, $1
represents a tabstop where your cursor will land after triggering the snippet. You can even add more of these to use multiple cursors; using $1
again in a different spot will create another cursor in that position, so you can place text in two places at the same time.
If you use $2
, $3
, etc. you can cycle your cursor between the tabstops in order of the numbers using, you guessed it, the tab key. Here’s an example of a javascript function declaration:
{
"JavaScript function": {
"prefix": "func",
"body": [
"/**",
" * ${3:Description of the function}",
" */",
"function ${1:functionName}(${2:parameters}) {",
" ${0:// function body}",
"}"
],
"description": "Create a JavaScript function with placeholders for name, parameters, and description"
}
}
You can use these tabstops to your advantage, making entering text into your triggered snippet super simple.
Injecting Data with Variables
VS Code also supports variables in your snippets, so you can inject metadata or contextual information automatically. The offered variables include metadata such as the current year or the filename, you can even inject random numbers and UUIDs. See here for a list of all the possible variables. Here’s an example of a snippet to create a new module header, with some injected metadata:
{
"JavaScript module header": {
"prefix": "module",
"body": [
"/**",
" * Module: ${TM_FILENAME_BASE}",
" * Description: ${1:Module description here}",
" * Author: ${2:Your Name}",
" * Created: ${CURRENT_YEAR}-${CURRENT_MONTH}-${CURRENT_DATE}",
" */",
"",
"export function ${3:mainFunction}() {",
" ${0:// Your code here}",
"}"
],
"description": "Create a JavaScript module with header info including filename, date, and author"
}
}
By utilizing just tabstops and variables, you can make some really dynamic and useful snippets. VS Code even offers more techniques, you can check out the official VS Code docs here for more advanced information.
Bringing it to the Team
Snippets can be incredibly useful for your personal development, but they can even save time for your team as a whole.
If your project team agrees to enforce a certain code style, you can check in your .code_snippets
file into your project’s git repo and share the snippets with your team members (who use VSCode). If your team is committed to use them, you can ensure consistency throughout your codebase while making it incredibly easy to adhere to the project’s style. Imagine the number of pull request comments you’d save!
Saving Time with Code Snippets
VS Code snippets are a simple but powerful feature that can enhance productivity and reduce time spent on repetitive code. By using a combination of built-in snippets, extensions, and customizations, you can streamline your coding experience, reduce errors, enforce a consistent code style across your team, and focus more on solving the bigger problems.