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:
- Preferences > Keyboard Shortcuts
- 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)
- 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
TM_SELECTED_TEXT
: The currently selected text or the empty string,TM_CURRENT_LINE
: The contents of the current line,TM_CURRENT_WORD
: The contents of the word under cursor or the empty string,TM_LINE_INDEX
: The zero-index based line number,TM_LINE_NUMBER
: The one-index based line number,TM_FILENAME
: The filename of the current document,TM_FILENAME_BASE
: The filename of the current document without its extensions,TM_DIRECTORY
: The directory of the current document,TM_FILEPATH
: The full file path of the current document,CLIPBOARD
: The contents of your clipboard,WORKSPACE_NAME
: The name of the opened workspace or folder.CURRENT_YEAR
: The current year,CURRENT_YEAR_SHORT
: The current year’s last two digits,CURRENT_MONTH
: The month as two digits (example ’07’),CURRENT_MONTH_NAME
: The full name of the month (example ‘July’),CURRENT_MONTH_NAME_SHORT
: The short name of the month (example ‘Jul’),CURRENT_DATE
: The day of the month,CURRENT_DAY_NAME
: The name of day (example ‘Monday’),CURRENT_DAY_NAME_SHORT
: The short name of the day (example ‘Mon’),CURRENT_HOUR
: The current hour in 24-hour clock format,CURRENT_MINUTE
: The current minute,CURRENT_SECOND
: The current second,CURRENT_SECONDS_UNIX
: The number of seconds since the Unix epoch.
Source for those variables: Visual Studio Code Snippets – the Definitive VS Code Snippet Guide for Beginners