Visual Studio Code Snippets

Visual Studio Code Snippets

Visual Studio Code supports snippets and there are numerous free snippets available in the marketplace. I was curious how to create custom user snippets and for kicks learned how to create a JavaScript snippet for writing stateless React components in Visual Studio Code. This example snippet can be applied to any custom code snippet you want to create in Visual Studio Code.

Visual Studio Code Snippets

While in Visual Studio Code press CMD-SHIFT-P to display the command palette and type the word "Snippet" and choose "Preferences: Snippets". Visual Studio Code Snippets are language dependent, so this will display a list of languages to select. For a JavaScript snippet, choose the JavaScript language.

Visual Studio Code Preferences Snippets

Visual Studio Code JavaScript Snippet

User snippets are stored in a JSON file by language. Once one selects "JavaScript" a file will be created ( or opened if JavaScript snippets have already been created ), called javascript.json. If this is the first time creating a JavaScript snippet, the file will be unsaved and contain some documentation to help understand the format for creating snippets.

I wanted to create a snippet to help code stateless components in React with properties. The React snippet is to create the following code by typing "rscp" ( React Stateless Component with Properties ) with appropriate tab stops.

import React, {PropTypes} from 'react';

const $name = (props) => {
    return (
        <div>
            
        </div>
    );
};

$name.propTypes = {

};

export default $name;

Here is the javascript.json file that allows me to do it.

{
  "Stateless Components": {
    "prefix": "rscp",
    "body": [
      "import React, {PropTypes} from 'react';",
      "",
      "const $1 = (props) => {",
      "\treturn (",
      "\t\t<div>",
      "\t\t\t$2",
      "\t\t</div>",
      "\t);",
      "};",
      "",
      "$1.propTypes = {",
      "\t$3",
      "};",
      "",
      "export default $1;"
    ],
    "description": "React Stateless Component with Properties"
  }
}

Now when I type "rscp" in a JavasScript file I can either choose the snippet from the context menu in the editor or press TAB to automatically expand it.

VSCode React.js Snippet

Visual Studio Code Tutorials

Here are a few other Visual Studio Code Tutorials I have written recently.