DEV Community

loading...
Cover image for How Pros Automate Repetitive Code using VS Code

How Pros Automate Repetitive Code using VS Code

Tapajyoti Bose
Top Rated Freelancer || Blogger || Cross-Platform App Developer || Web Developer || Open Source Contributor
Updated on ・5 min read

While Programming, you are bound to encounter Repetitive Code, writing which is a complete waste of time. I am not talking about Non-DRY Code, but Essentials Code that is necessary to be written. An example of this would be connecting State/Dispatch to Props using React-Redux.

Anyone who has worked on a decent-sized React-Redux project knows how many times you have to write the same code to connect the Redux Store Data to the Component Props.

Today we are going to fix that and provide you with a way to streamline ANY Repetitive Code you have and Maximize your Productivity.

What are Snippets in VS Code?

VS Code is an Amazing Code Editor that provides a plethora of tools to take your productivity to the next level. Snippets are just one such tool.

Snippets can be thought of as Templates that enable you write code once and reuse it, as per requirement. It allows Variables as well as Dynamic User Inputs.

If you have been using VS Code for some time, you are bound to come across Snippets.

Snippet

Some Snippets come pre-built with VS Code. You can install some extensions to add event more Snippets, but most importantly, you can create your own Snippets to cater to your very own needs.

Creating our first Snippets

Creating a Snippets is fairly simple:

  1. Go to File > Preferences > User Snippets (possibly Code > Preferences > User Snippets on macOS).

    Or you might use F1 to bring up the Command Palette and search for User Snippets

  2. Select the type of Snippet you want to create (language-specific, project-specific or global)

    Snippet Creation

  3. Add the following in the created .code-snippets file

    {
    "Signature": {
            "scope": "html",
            "prefix": "hello",
            "body": [
                "Hello!!!"
            ],
            "description": "Hello"
        }
    }
    
  4. Done! Now when you type "hello" in an HTML file, you would be to use the Snippet

This wasn't a practical example, but we did manage to get our feet wet at making Snippets.

On inspecting the Snippet definition, we find the scope that declares which files the Snippet should be used in. The prefix mentions the prefix text that will trigger the Snippet to show up. The body defines the body of the Snippet(each line of the Snippet would be a new string in array). And finally, description is a short description of the Snippet's function.

Let us make a couple of practical ones to deepen our understanding and solve the issue mentioned in the Intro of the article (connecting State/Dispatch to Props using React-Redux).

Snippet 1: Leaving a Signature

Let's try making a snippet that leaves a signature like this in any file and isn't restricted to only Python

"""
Name: Tapajyoti Bose
Modified on: 05 September 2021 08:38:35
"""
Enter fullscreen mode Exit fullscreen mode

We would also like the Snippet to update the date and time dynamically, of course.

Luckily, VS Code provides a bunch of variables for this purpose.

We would be using BLOCK_COMMENT_START and BLOCK_COMMENT_END to automatically generate the block comments for any language and CURRENT_DATE, CURRENT_MONTH_NAME, CURRENT_YEAR, CURRENT_HOUR, CURRENT_MINUTE, & CURRENT_SECOND to generate the date and time dynamically.

NOTE: To get the complete list of variables, click here

So the Snippet would initially look like this:

"Signature": {
    "scope": "python,javascript,typescript,html,css",
    "prefix": "signature",
    "body": [
        "$BLOCK_COMMENT_START",
        "Name: Tapajyoti Bose",
        "Modified on: $CURRENT_DATE $CURRENT_MONTH_NAME $CURRENT_YEAR $CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND",
        "$BLOCK_COMMENT_END"
    ],
    "description": "Leave a signature"
}
Enter fullscreen mode Exit fullscreen mode

Now within Python, Javascript, Typescript, HTML, CSS files, you would be able to leave a signature.

Signature

You might be wondering if extending the functionality to all languages would require you to add the names of all languages. Luckily there is an easy solution: just remove the scope from the Snippet definition and Viola! the functionality is extended to all languages!

Snippet 2: Connecting Redux to React Props

This is even easier than the Signature Snippet. Just copy the following code in the snippet definition, and you are done:

"Connect Component to Redux": {
    "scope": "javascriptreact,typescriptreact",
    "prefix": "connect",
    "body": [
        "const mapStateToProps = (state) => ({",
        "\t$1",
        "})",
        "",
        "const mapDispatchToProps = (dispatch) => ({",
        "\t$0",
        "})",
        "",
        "export default connect(mapStateToProps, mapDispatchToProps)($TM_FILENAME_BASE)"
    ],
    "description": "Connect React Component to Redux"
}
Enter fullscreen mode Exit fullscreen mode

Let us examine what is being done.

We are scoping the Snippet to React based projects for obvious reasons.

In the body, you might be seeing $0 and $1 for the first time. These are placeholders for tab-able positions where the user should enter their own logic (the parts of the store they want to connect to the props in this case).

We are using the File Name as the Component Name, as in most cases, the convention is using the Component Name to be the same as the File Name.

Wrapping Up

In this article, we went over how you can Automate Repetitive Code using VS Code Snippets. Now you can create Custom Snippets that solve your own problems and boost your productivity to new heights.

Happy Developing!

Thumbs Up

Thanks for reading

Want to work together? Contact me on Upwork

Want to see what I am working on? Check out my GitHub

I am a freelancer who will start off as a Digital Nomad in mid-2022. Want to catch the journey? Follow me on Instagram

Follow my blogs for weekly new tidbits on Dev

FAQ

These are a few commonly asked questions I get. So, I hope this FAQ section solves your issues.

  1. I am a beginner, how should I learn Front-End Web Dev?
    Look into the following articles:

    1. Front End Development Roadmap
    2. Front End Project Ideas
  2. Would you mentor me?

    Sorry, I am already under a lot of workload and would not have the time to mentor anyone.

  3. Would you like to collaborate on our site?

    As mentioned in the previous question, I am in a time crunch, so I would have to pass on such opportunities.

Connect to me on

Discussion (8)

Collapse
stevereid profile image
Steve Reid • Edited

I use vscode every day and snippets are a great timesaver. However we also use redux in our tech stack and haven’t used that redux connect pattern for nearly 2 years. I’d be surprised if anyone is still using it today.

Collapse
ruppysuppy profile image
Tapajyoti Bose Author

Then how do you share the redux store data with the components?

Collapse
stevereid profile image
Steve Reid

Here you go, straight from the horse’s mouth.
twitter.com/acemarke/status/143339...

Thread Thread
ruppysuppy profile image
Tapajyoti Bose Author

That's using redux toolkit (createSlice isn't available with plain old redux). But thanks for your input. It led me to coming across the useSelector and useDispatch, which does look like the future of react-redux to me

Collapse
hyoretsu profile image
Aran Leite

marketplace.visualstudio.com/items...
Actual pros, that extension automatically applies snippets when creating files.

Collapse
ruppysuppy profile image
Tapajyoti Bose Author

Thanks for sharing this Aran. It is of great help for competitive coding due to the common structure of the template, but for development purpose, you will be working against it a lot of the time. Eg: a .ts can store shared variables, interfaces or even redux reducers, so finding the context for the .ts would be a tad difficult

Collapse
hyoretsu profile image
Aran Leite • Edited

Not actually, since you can tweak it by regex. I've got different templates for styled-components, DB entities, interfaces, Express controllers/routes, services, and even Jest files. They all either have a unique prefix/suffix or are under a specific folder.

Thread Thread
ruppysuppy profile image
Tapajyoti Bose Author

Yeah, its a nice one. Thanks for sharing!