DEV Community

Cover image for Create custom code snippets in VsCode
Abayomi Ogunnusi
Abayomi Ogunnusi

Posted on

7 1

Create custom code snippets in VsCode

Programming, in itself, can become very repetitive no matter how **DRY **you aim to be.

dry

To address this, we must learn how to reduce the number of keystrokes we type. I will show you how to create a custom snippet in VS Code in just four steps.

  1. Press Ctrl + Shift + P (Windows/Linux) or Cmd + Shift + P (Mac).

Image description

  1. Type Preferences: Configure User Snippets and select it.

Image description

  1. Choose the language for the snippet (I will choose typescript.json for TypeScript).

Image description

  1. Paste the following configuration into the snippet file to create a console.log snippet:
{
"Console Log": {
    "prefix": "cl",
    "body": [
      "console.log($1);", // $1 possible variable placeholder
      "$2", // for tab stop i.e. to place cursor,
      "$0" // for final cursor position
    ],
    "description": "Console log snippet"
}
Enter fullscreen mode Exit fullscreen mode
  • "prefix": This is the shortcut you type (e.g., cl).
  • "body": This is the code that will be inserted. $1 is a placeholder for where your cursor will be placed after expanding the snippet.
  • "Description": A short description of the snippet (optional).

Testing

To test, create a new .ts file and type cl anywhere.

Image description

Other examples include:

Function Declaration

{
  "Function Declaration": {
    "prefix": "fn",
    "body": [
      "function $1($2) {",
      "  $3",
      "}",
      "$0"
    ],
    "description": "Function declaration snippet"
  }
}
Enter fullscreen mode Exit fullscreen mode

Try-Catch Block

{
  "Try-Catch Block": {
    "prefix": "tc",
    "body": [
      "try {",
      "  $1",
      "} catch (error) {",
      "  console.error(error);",
      "  $2",
      "}",
      "$0"
    ],
    "description": "Try-catch block snippet"
  }
}
Enter fullscreen mode Exit fullscreen mode

Import Statement

{
  "Import Statement": {
    "prefix": "imp",
    "body": [
      "import $1 from '$2';",
      "$0"
    ],
    "description": "Import statement snippet"
  }
}
Enter fullscreen mode Exit fullscreen mode

Now that you know this, you can work smarter, finish your tasks, and go on vacation.

vacation

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video