VS Code Snippets – How to Code Easier and Faster?
Tags: vscode, snippets
Published: 2021-05-11 21:13:04

<!-- wp:paragraph {"style":{"typography":{"fontSize":30}}} -->
<p style="font-size:30px">How can you make your coding easier with VS Code Snippets?</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2><strong>INTRO - let’s get some theory</strong></h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4><strong>What are VS Code Snippets?</strong></h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Snippets are kind of templates which contain repeated or commonly used parts of code for instance loops, if statements, basic component code etc. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Whether our code is really generic, we often need to repeat some parts of it like creating new components, reducers, actions creators… </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>And, to do not create those functionalities manually, we should use SNIPPETS that automatically generate commonly used code.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We have a few types of snippets such as built in, plugged in (from VS Code extensions) and custom (created by ourselves).</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4><strong>Where can we find VS Code Snippets?</strong></h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>VS Code provides two ways of getting snippets.<strong> </strong>Snippets are available by clicking<em> <code>ctrl + space</code></em> or we can type “Insert Snippet” in the command line <code>(cmd+shift+p)</code>. After both actions we will be able to see the whole list of our snippets.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4><strong>How the snippet look like?</strong></h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Let’s analyze how snippet looks like. First of all it has a JSON structure. It has a few mandatory fields like <code>“name”</code>, <code>“prefix”</code> and <code>“body”</code>. We can also use some additional properties like <code>“scope”</code>, <code>“description”</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:code-mind/code {"code":"{\n \u0022name\u0022: {\n   \u0022scope\u0022: \u0022typescriptreact\u0022,\n   \u0022prefix\u0022: \u0022crcf\u0022,\n   \u0022body\u0022: []\n   \u0022description\u0022: \u0022\u0022\n }\n","lang":"JSON"} -->
<pre class="wp-block-code-mind-code c-code"><code class="json">{
 "name": {
   "scope": "typescriptreact",
   "prefix": "crcf",
   "body": []
   "description": ""
 }
</code></pre>
<!-- /wp:code-mind/code -->

<!-- wp:paragraph -->
<p><br><code>“name”</code> - the name of our snippet. It’s displayed if we do not provide a description field.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><code>“scope”</code> - defines snippet availability. In other words, in what types of files our snippet should be available. (If we do not provide this value, we can have access to it within all files. However, if we for instance provide a value such as “typescriptreact” we will be able to invoke our snippet only in files which have “.tsx” extension.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><code>“prefix”</code> - shortcut, lets us invoke snippet in file using shorter syntax.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><code>“body”</code> -  repeated/common parts of code.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><code>“description”</code> - describes what our snippet does.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>VS Code <strong>Snippet syntax</strong></h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><strong>Tabstops</strong><br>In our snippet’s body we are able to use tabstops - places where our cursor will be stopped to provide a value. We define tabstops by &nbsp;<code>$1</code>, <code>$2</code>. We can use same indicators in many places in our code - they will be updating synchronously.</li></ul>
<!-- /wp:list -->

<!-- wp:list -->
<ul><li><strong>Placeholders</strong><br>It is a tabstop with a default value <code>${1:defaultValue}</code>. This value can be editable as well. We are able to inject one placeholder into another ${1:first ${2:second}}.</li></ul>
<!-- /wp:list -->

<!-- wp:list -->
<ul><li><strong>Choices</strong><br>We can use placeholders with predefined values. We need to select during tabstop one of provided values like <code>${1|one,two,three|}</code>. We are not able to provide there another value instead of those defined in select.<br></li><li><strong>Variables</strong><br>Using <code>$name</code>, you can insert the value of a variable. When a variable isn't set, its default or the empty string is inserted. When a variable is unknown (that is, its name isn't defined) the name of the variable is inserted, and it is transformed into a placeholder. The following variables can be used: <code>TM_FILENAME, TM_FILENAME_BASE</code> and so on. More available variables you can check <a href="https://code.visualstudio.com/docs/editor/userdefinedsnippets#_variables" target="_blank" rel="noreferrer noopener nofollow">here</a>.</li></ul>
<!-- /wp:list -->

<!-- wp:list -->
<ul><li><strong>Transformations</strong><br>Allow us to modify the value of a variable before it is inserted by using the regular expression <code>${TM_FILENAME_BASE/[\\.]/_/}</code> - replace first . by <code>_</code>. <code>${TM_FILENAME_BASE/\\index/componentName/}}</code> - replace file name index to placeholder <code>componentName</code>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2><strong>BASICS - let’s have some practise</strong></h2>
<!-- /wp:heading -->

<!-- wp:image {"align":"center"} -->
<div class="wp-block-image"><figure class="aligncenter"><img src="https://lh5.googleusercontent.com/0LIcFzNnytNlJ_rVtrvDSybrwp4y4CVlRQx8CjzWjMANx9vcQaXBz-gEaE1I7g5EnLtkd3AN53rKzkbR8tKq30bAfbGTndn-9U33ympL7FAKua7T_TacuTE9pWL9rdOCe0RmZy6J" alt="Sponge Bob on coding without VS Code Snippets"/></figure></div>
<!-- /wp:image -->

<!-- wp:heading {"level":4} -->
<h4><strong>How can we use VS Code snippets?</strong></h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>I've made a snippet which creates a functional component based on the file name. However, if the file will be calling for index, the programmer should pass the name of the component by himself.</p>
<!-- /wp:paragraph -->

<!-- wp:columns -->
<div class="wp-block-columns"><!-- wp:column {"width":"100%"} -->
<div class="wp-block-column" style="flex-basis:100%"><!-- wp:code-mind/code {"code":"{\n \u0022createFunctionalComponent\u0022: {\n   \u0022scope\u0022: \u0022typescriptreact\u0022,\n   \u0022prefix\u0022: \u0022crfc\u0022,\n   \u0022body\u0022: [\n     \u0022import React from 'react';\u0022,\n     \u0022\u0022,\n     \u0022const ${1:${TM_FILENAME_BASE/\\\\index/componentName/}}: React.FC = () =\u003e {\u0022,\n     \u0022  return (\u0022,\n     \u0022    \u003cdiv\u003e\u0022,\n     \u0022      $0\u0022,\n     \u0022    \u003c/div\u003e\u0022,\n     \u0022  );\u0022,\n     \u0022}\u0022,\n     \u0022\u0022,\n     \u0022export default ${1:${TM_FILENAME_BASE/\\\\index/componentName/}};\u0022\n   ],\n   \u0022description\u0022: \u0022Create functional component based on file name with types\u0022\n }\n}\n","lang":"JSON"} -->
<pre class="wp-block-code-mind-code c-code"><code class="json">{
 "createFunctionalComponent": {
   "scope": "typescriptreact",
   "prefix": "crfc",
   "body": [
     "import React from 'react';",
     "",
     "const ${1:${TM_FILENAME_BASE/\\index/componentName/}}: React.FC = () => {",
     "  return (",
     "    &lt;div>",
     "      $0",
     "    &lt;/div>",
     "  );",
     "}",
     "",
     "export default ${1:${TM_FILENAME_BASE/\\index/componentName/}};"
   ],
   "description": "Create functional component based on file name with types"
 }
}
</code></pre>
<!-- /wp:code-mind/code --></div>
<!-- /wp:column --></div>
<!-- /wp:columns -->

<!-- wp:heading -->
<h2><strong>EXTENDS - let’s practise more</strong></h2>
<!-- /wp:heading -->

<!-- wp:image {"align":"center"} -->
<div class="wp-block-image"><figure class="aligncenter"><img src="https://lh6.googleusercontent.com/rsxxkmIG1uuhYF1i2t2h5DdrQvsJwbcaoSJYT-rzvSu95joSN0o3WMEXks-zEYCMX_q0aqKQr5_BpVz2y7yarhuQAQ7ZkZ1kux8Pk3xga8m_KD8P8B67mH0HRI4k5S5WaxipdqCA" alt="Sponge Bob is happy about coding with VS Code Snippets "/></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Let’s think about an application where we use React and Redux as a state manager. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The main goal of our app is displaying statistics, for instance, in tables. We need to handle every data in Redux - every time when we create a new table we should do reducer, actions, some const files, and so on. So every time we will duplicate the same code, but with different variable names. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>How can we optimize that? Of course by creating snippets. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>After that, instead of spending many hours on creating a new table and copy&amp;paste code from previous tables and renaming variables we will spend only a few minutes to create a new table and test our changes.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:image -->
<figure class="wp-block-image"><img src="https://lh5.googleusercontent.com/J8y8aO7rFsJD3AcgpnV4cPyUfrZLjNH78nVTuE_9F5mczL36V1NMUzQOXe4cImQEA57rVX8_oErKLBaZomlzV08mVvrxjMtGG-wcEeHT45Kd7AlhD3Hn6imy-knVRdcczDxM2Kt9" alt="gif with an example on how to use VS Code snippets"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>You can easily create snippets by using <a href="https://snippet-generator.app/">https://snippet-generator.app/</a>.   Earlier I didn't use snippets at all. I even didn't know that I can create my own snippets. Since I used them, I have been a huge fan of them! They very speed up your work and make coding easier. Try to play with them, it is worth it! :D</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We have also made another article on <a href="https://pagepro.co/blog/vs-code-tricks-how-to-work-faster/" target="_blank" rel="noreferrer noopener">VS Code Tricks, and how to make your coding work much easier</a>! </p>
<!-- /wp:paragraph -->