Easily Boost Your Productivity With Code Snippets in VSCode

Abdul Rahman / September 22, 2021

3 min read999 views

What is Code Snippet?

A code snippet is basically a small portion of a highly reusable code, so if you have a repeating code around your codebase like library imports, or a boilerplate in your app that you find yourself typing over and over again, that's where code snippets comes in 😉

So, How do I get started?

Cool, so to get started with code snippets, you can do it without any setup at all, you can just download an extension that fits your liking.

Using an Extension

For example, one of the popular ones is React Snippets, after you get the extension you can have a list of snippets in your React project!

But it doesn't stop there, to maximize your productivity, you can create a custom code snippet in your project!

Custom Code Snippet

Let's say you have some thing very specific in your project that you repeat over and over again,

In my case, inside my React Native project all my screens have this design.

So, I have to repeat this code everytime I create a new screen.

import React from 'react'
import PageContainer from 'components/PageContainer'
import NavHeader from 'components/NavHeader'

import { Text } from 'native-base'

export default function Homepage() {
  return (
    <PageContainer header={<NavHeader title="Homepage" />}>
      <Text>Hello World</Text>
    </PageContainer>
  )
}

We can create a custom snippet for that!

Creating a custom code snippet is very easy, you can go to https://snippet-generator.app/, give the description, tab trigger, and your code!

One thing to note here is I used ${1:${TM_FILENAME_BASE}}, which returns the current file name! It's one of the most common snippets variable in VSCode.

Where do I put the snippets?

You can do CTRL + SHIFT + P and search for User Snippet, then choose Preferences: Configure User Snippets.

Then, you'll see an options to where your code snippets lives on, you can choose whether your code snippet lives globally, project only, or language specific.

In this case we'll choose New Snippets file for 'my-project', give the snippet a name, and copy the snippet from the snippets generator inside the object.

{
  "common page": {
    "prefix": "rfpage",
    "body": [
      "import React from 'react'",
      "import PageContainer from 'components/PageContainer'",
      "import NavHeader from 'components/NavHeader'",
      "",
      "import { Text } from 'native-base'",
      "",
      "export default function ${1:${TM_FILENAME_BASE}} () {",
      "",
      "  return (",
      "  <PageContainer header={<NavHeader title=\"${1:${TM_FILENAME_BASE}}\"/>}>",
      "    <Text>Hello World</Text>",
      "  </PageContainer>",
      "  )",
      "}"
    ],
    "description": "common page"
  }
}

That's it, Now you can use it throughout your project!

Designed and Developed by Abdul Rahman.
Built with Next.js & Chakra UI. Hosted on Vercel.