How to Add Custom Shortcuts and Code Snippets to VS Code by@alexadam

How to Add Custom Shortcuts and Code Snippets to VS Code

On Linux, go to: File - Preferences - KeyboardShortcuts - Open Keyboard Shortcuts JSON (top-right icon) Add custom key bindings like this: `Ctrl+D` to duplicate line / selection. `Credo+Shift+L` to insert a `console.log` with the clipboard's content. To use the snippets, open a `tsx` file and type react or rcp - you'll see the snippets' names in the auto-complete pop-up.
image
Alex Adam HackerNoon profile picture

Alex Adam

Creative Coder


Keyboard Shortcuts

On Linux, go to:


File -> Preferences -> KeyboardShortcuts -> Open Keyboard Shortcuts JSON (top-right icon)


On Mac:


Code -> Preferences -> KeyboardShortcuts -> Open Keyboard Shortcuts JSON (top-right icon)


Then add custom key bindings like this:


Ctrl+D to duplicate line / selection:


{
  "key": "ctrl+d",
  "command": "editor.action.duplicateSelection"
}


Ctrl+Shift+L to insert a console.log with the selected text:


{
  "key": "ctrl+shift+l",
  "command": "editor.action.insertSnippet",
  "when": "editorTextFocus",
  "args": {
    "snippet": "console.log('${TM_SELECTED_TEXT}$1')$2;"
  }
}


Or Ctrl+Shift+L to insert a console.log with the clipboard's content:


{
  "key": "ctrl+shift+l",
  "command": "editor.action.insertSnippet",
  "when": "editorTextFocus",
  "args": {
    "snippet": "console.log('${CLIPBOARD}', ${CLIPBOARD})"
  }
}


More useful variables: https://code.visualstudio.com/docs/editor/userdefinedsnippets#_variables


Code Snippets

To add some React Component code snippets, on Linux, go to:


File -> Preferences -> Configure User Snippets -> search for TypescriptReact


On Mac:


Code -> Preferences -> Configure User Snippets -> search for TypescriptReact


Then paste this in the json file:


 "New React Component": {
  "prefix": ["react-component", "rc"],
  "body": ["const ${1} = () => {\n\treturn (\n\t\t<div>\n\n\t\t\n\t)\n}\n\nexport default ${1}"],
  "description": "New React Component"
 },
 "New React Component With Props": {
  "prefix": ["react-component-props", "rcp"],
  "body": ["interface I${1}Props {\n\t\n}\n\nconst ${1} = (props: I${1/(.*)/${1:/capitalize}/}Props) => {\n\treturn (\n\t\t<div>\n\n\t\t\n\t)\n}\n\nexport default ${1}"],
  "description": "New React Component With Props"
 }


To use the snippets, open a tsx file and type react or rcp -> you'll see the snippets' names in the auto-complete pop-up.


Code output example (you can edit the component's name):


const Comp1 = () => {
  return (
    <div>

    </div>
  )
}

export default Comp1

// and

interface IComp2Props {
  
}

const Comp2 = (props: IComp2Props) => {
  return (
    <div>

    </div>
  )
}

export default Comp2


More: https://code.visualstudio.com/docs/editor/userdefinedsnippets



Also published here.

react to story with heart
react to story with light
react to story with boat
react to story with money
L O A D I N G
. . . comments & more!