Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactor local variable name using Visual Studio Code

People also ask

How do you change the same variable in VS Code?

If you select a variable/method and hit F2, you can edit the name and it will change every instance of that variable's name throughout the entire current working project.

How do I change my name in Visual Studio?

You can find and replace text in the Visual Studio editor by using Find and Replace (Ctrl+F or Ctrl+H) or Find/Replace in Files (Ctrl+Shift+F or Ctrl+Shift+H).

What is Refactor in VS Code?

Source code refactoring can improve the quality and maintainability of your project by restructuring your code while not modifying the runtime behavior. Visual Studio Code supports refactoring operations (refactorings) such as Extract Method and Extract Variable to improve your code base from within your editor.


Use rename symbol instead of the standard find/replace. Rename is bound to F2 by default.

Rename symbol will know to only touch the local roles references in your example. Visual Studio Code ships with rename support for JavaScript and TypeScript. Other languages may require installing a language extension.


Use Rename Symbol. It is defined by default with Ctrl + F2.

However, keep in mind that the variable, definition, function, etc., that you're changing, will be changed in the file itself, not only the scope. Visual Studio Code for now doesn't have an implementation for renaming a variable in a scope (for example, a variable inside a function). So keep that in mind.

Visual Studio Code - change all occurrences


For macOS users: Use Fn + + F2 to rename a variable inside a code block.


To open your user and workspace settings, use the following Visual Studio Code menu command:

On Windows/Linux: Menu FilePreferencesSettings. On macOS: CodePreferencesSettings.

You can also open the Settings editor from the Command Palette (Ctrl + Shift + P) with Preferences, open Settings or use the keyboard shortcut (Ctrl + ,).

Enter image description here

In the search bar, enter keybindings.json, and add this below code:

{
  "command": "editor.action.changeAll",
  "key": "ctrl+f2",
  "when": "editorTextFocus && !editorReadonly"
}

and

{
  "command": "editor.action.rename",
  "key": "f2",
  "when": "editorHasRenameProvider && editorTextFocus && !editorReadonly"
}

In the keybindings.

F2 appears to work across all files, and Ctrl + F2 in the current file only.