Quick VS Code refactor/productivity trick
Stephen Chiang
Posted on August 8, 2019
So I was browsing Dev.to , like I normally do while waiting for my build process to finish (🐱👤) and I saw this post:
5 Visual Studio Code Tricks to Boost Your Productivity
hexrcs ・ Aug 8 '19
And I thought I would share my one of my favorites.
Often when I need to create an object and as a test or have common values except for a single character I use this flow. It also works in refactoring just pieces of code really fast.
Here's an example, let's say i have an array of objects where I want the values to be 'test1', 'test2', 'test3' respectively to each object in the array:
const test = 'test';
const objectArray = [
{
prop1: 'test`,
prop1: 'test`,
prop1: 'test`,
prop1: 'test`,
},
{
prop1: 'test`,
prop1: 'test`,
prop1: 'test`,
prop1: 'test`,
},
{
prop1: 'test`,
prop1: 'test`,
prop1: 'test`,
prop1: 'test`,
},
];
In this case you could just use a multi-cursor and type in the numerical value at the end, but here's another way that that helps out when it's not so easy.
You could use the ctr + h
to replace test
with test1
, but that could replace more than what you had intended, like the string variable called test
above objArray
.
So here's what I do:
- Select the block of code using some combination of
shift
,ctrl
andarrow keys
that is most appropriate. -
alt + l
(this notifies vs code that you intend to only do this operation on the selected block. -
ctrl + h
(opens the find/replace dialog box) - type in the value to be replaced
- tab over to type in the value to be replaced
-
ctrl + enter
. *update: new version of VS Code defaults toctrl + alt + enter
but can be changed back in they keyboard shortcuts - repeat for the next block
🔥For me, this is quite fast once the pattern becomes natural.
Voila❗ now it should look like the following:
const test = 'test';
const objectArray = [
{
prop1: 'test1`,
prop1: 'test1`,
prop1: 'test1`,
prop1: 'test1`,
},
{
prop1: 'test2`,
prop1: 'test2`,
prop1: 'test2,
prop1: 'test2,
},
{
prop1: 'test3`,
prop1: 'test3`,
prop1: 'test3`,
prop1: 'test3`,
},
]
And your fingers never had to leave the keyboard, cheers! 🍻
If you find this valuable, please leave a comment and follow me on Dev.to @chiangs and Twitter @chiangse, 🍻 cheers!
Posted on August 8, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.