Site icon Denis Bouquet

Visual Studio Code, insert console.log snippet with a keyboard shortcut

I like using a shortcut to add console.log statement using my code editor. When switching from Sublime Text to VS Code, I looked into recreating a snippet to insert a console.log with a shortcut. Here is the snippet to bind a keyboard shortcut to create a console log statement.

Console.log snippet in Visual Studio Code (insert with keyboard shortcut)

Follow those steps:

  1. Preferences > Keyboard Shortcuts
  2. Above the search bar on the right you’ll see the icon for Open keyboard shortcuts (JSON), click on it (rollover icons to see the name)
  3. Add this to the JSON settings:
// Place your key bindings in this file to override the defaults
[
    {
        "key": "cmd+e",
        "command": "editor.action.insertSnippet",
        "when": "editorTextFocus",
        "args": {
            "snippet": "console.log('=== ${TM_SELECTED_TEXT}$1 ${TM_FILENAME} [${TM_LINE_NUMBER}] ===', ${TM_SELECTED_TEXT}$1)$2;"
        }
    }
]

Pressing CMD+E will output the console snippet. Also, if you already have text selected, it will be put inside the log statement.

You can change this keyboard key to whatever you wish, I like CMD+E.


Variables you can use in VS Code

Source for those variables: Visual Studio Code Snippets – the Definitive VS Code Snippet Guide for Beginners

Exit mobile version