Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 26, 2022 06:25 pm GMT

How to create VS Code code snippet

Code snippets for the rescue

You know those repetitive tasks that you look and think: it should be great to never write this again (or memorize).
Code snippets could be so powerful, you should learn this asap!

A code snippet is a block of predefined text that you can customize with some inputs.

Creating a global code snippet

Today i will show you one of my new favorites code snippets: react context with typescript.
If you have to write some of those anytime, you know that could be a little bit confusing(to say lea``st).

First of all, lets see a basic react context setup to understand the power of this code snippet:

Image a piece of code

Alright, now that we know how to write a basic(not so basic) react context with typescript, it should be nice to have an code snippet and never write all os these lines again. Lets do this!

To create a global code snippet, open VS Code and follow these steps:

  • press ctrl+shift+p
  • type: snippet
  • select Configure code snippet
  • select new global snippets file

Now you have a new global code snippet file! Cool!
A code snippet file its just a json with some informations about the snippet, like its name, the shortcut to use it and the body.
Heres the react context code snippet, just paste it in the new file and save:

`
{
"create react context": {
"scope": "typescriptreact",
"prefix": "tscontext",
"body": [
"import { createContext, useContext, PropsWithChildren } from 'react';",
"",
"type $1Type = {}",
"",
"export const $1 = createContext({} as $1Type)",
"",
"export const $1Provider = ({ children }: PropsWithChildren) => {",
" return (",
" <$1.Provider value={{}}>",
" {children}",
" </$1.Provider>",
" );",
"}",
"",
"export const use$1 = () => useContext($1)"
],
"description": "create react context with hook"
}
}
`

To use it, create an .tsx file, type tscontext than hit tab. Choose the context name (ie: BasicContext) and hit esc.
And thats it, the snippet will fill all variables/types/function names according to the name that you choose.

Snippet scope

On VS Code, snippets could be global or scoped to the project. You could select the scope after selecting Configure code snippet step.

Extension

Theres an amazing VS Code extension with a bunch of code snippets for React. Take a look, it is really great!

Thank you for the attention, bye.


Original Link: https://dev.to/lucasvsouza28/how-to-create-vs-code-code-snippet-22lg

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To