Open In App

How to create the boilerplate code in VS Code?

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++ 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:

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




// 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"
    }
}

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:


Article Tags :