Something I find myself doing a lot in the Javascript/Node/TypeScript world is logging out an object to the console. But of course if you're not careful you end up logging the oh-so-useful [Object object], so you need to wrap your thing in JSON.stringify() to get something readable.
I got heartily sick of doing this so created a couple of custom keybindings for VS Code to automate things.
Wrap in JSON.stringify - [ Cmd + Shift + J ]
Takes the selected text and wraps it in a call to JSON.stringify() with null, 2 as the second and third args to make it nicely indented (because why not given it's a macro?); e.g.:
console.log(`Received backEndResponse`)becomes:
console.log(`Received ${JSON.stringify(backEndResponse, null, 2)}`)
Label and Wrap in JSON.stringify - [ Cmd + Shift + Alt + J ]
As the previous macro, but repeats the name of the variable with a colon followed by the JSON, for clarity as to what's being logged; e.g.:
console.log(`New localState`)becomes:
console.log(`New localState: ${JSON.stringify(localState, null, 2)}`)
How do I set these?
On the Mac you can use ⌘-K-S to see the pretty shortcut list, then hit the "Open Keyboard Shortcuts (JSON)" icon in the top-right to get the text editor to show the contents of keybindings.json. Then paste away!
// Place your key bindings in this file to override the defaults [ { "key": "cmd+shift+j", "command": "editor.action.insertSnippet", "when": "editorTextFocus", "args": { "snippet": "JSON.stringify(${TM_SELECTED_TEXT}$1, null, 2)" } }, { "key": "cmd+shift+alt+j", "command": "editor.action.insertSnippet", "when": "editorTextFocus", "args": { "snippet": "${TM_SELECTED_TEXT}: ${JSON.stringify(${TM_SELECTED_TEXT}$1, null, 2)}" } } ]
No comments:
Post a Comment
Comments welcome - spam is not. Spam will be detected, deleted and the source IP blocked.