Open In App

How to create the boilerplate code in VS Code?

Improve
Improve
Like Article
Like
Save
Share
Report

While programming, there is often a piece of code that needs to be written repetitively. For example, loops (for loop, while loop, do-while loop), or classes and functions. To write such a piece of code, again and again, becomes a daunting task, and often copy and paste is done, which definitely takes a lot of time and effort. The above problem can be solved using Code-Snippets or boilerplates.

Boilerplate or a code-snippet are solution provided by IDEs like VS Code, where a repetitive code can be called within a program by typing prefix names.

Code snippets for loops and classes are already provided in the IDE.

C++




// C++ program to demonstrate the
// boilerplate code
#include <iostream>
using namespace std;
  
// Driver Code
int main()
{
    return 0;
}


Let’s see how to create a Code-Snippet/ Boilerplate for our basic C++ programs in the VS Code.

Step 1: Locating the C++ JSON file for adding the snippet:

  • Open your VS Code and click on the settings button in the bottom-left corner.

VS code

  • Click on User Snippets.

Click on user snippets

  • You’ll see a dropdown at the top of a list of various JSON files.

list of JSON files

  • Click on cpp.json

Step 2: Adding the C++ code to the JSON file:

  • Remove all the code from this file and write down the code given below.

C++




// Write this code in the cpp.json file
{
    "cpp snippets":
    {
        "prefix" : "boilerplate",
                   "body" : [
                       "#include<iostream>",
                       "using namespace std;",
                       "int main()",
                       "{",
                       "    return 0;",
                       "}"
  
                   ],
                            "description" : "to produce the main snippet for cpp"
    }
}


Add C++ code in JSON file

  • After writing the code, press Ctrl + S to save the changes that have been made.

Explanation of the above code:

  1. prefix: It is used to trigger the snippet or the boilerplate ( Your boilerplate can have any random name, here I have used ‘boilerplate’ itself)
  2. body: It contains the reusable code, which we’ll call with the help of a prefix.
  3. description: It contains a small definition of the snippet, which explains the purpose behind it.

Step 3: Calling the Boilerplate in our program:

  • Create a new C++ file in the current folder. Type in the prefix which we used for our Boilerplate. You will notice that VS Code automatically suggests your prefix name while you are halfway typing the name.
  • Now press ENTER.

Calling boilerplate in program

  • Now we have created a basic boilerplate for everyday programming.

Create a basic boilerplate



Last Updated : 31 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads