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.
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.
- Click on User Snippets.
- You’ll see a dropdown at the top of a list of various 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.
- After writing the code, press Ctrl + S to save the changes that have been made.
Explanation of the above code:
- prefix: It is used to trigger the snippet or the boilerplate ( Your boilerplate can have any random name, here I have used ‘boilerplate’ itself)
- body: It contains the reusable code, which we’ll call with the help of a prefix.
- 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.
- Now we have created a basic boilerplate for everyday programming.