JetBrains Rider 2018.1 Help

Refactoring JavaScript

Refactoring means updating the source code without changing the behaviour of the application. Refactoring helps you keep your code solid, dry, and easy to maintain.

Move refactorings

Besides moving files and folders, JetBrains Rider lets you move JavaScript top-level symbols. The Move Symbol Refactoring works for classes, functions, and variables in ES6 modules.

To move a class, a function, or a variable

  1. Select the symbol to move.
  2. Press Ctrl+R, O or choose Refactor | Move on the context menu or on the main menu.
  3. In the dialog box that opens, specify the destination file.

In the example below, the function changeSelectedPlaylists is moved from the PlayerActions.js file to the PlaylistsActions.js file. Note that an import statement for the types that changeSelectedPlaylists requires is added to PlaylistsActions.js. Also all the imports of changeSelectedPlaylists in the other files are updated.

Pull Class Members Up refactoring

The Pull Class Members Up refactoring moves class methods upwards in the class hierarchy – from the current class to a superclass.

Example: moving a class method to a superclass
Suppose you have a class AccountingDepartment that extends an abstract class Department.

class Department { name; printName() { console.log("Department name: " + this.name); } } class AccountingDepartment extends Department { printMeeting() { console.log("The Accounting Department meets each Monday at 10am."); } generateReports() { console.log("Generating accounting reports..."); } }

In this example, the Pull Class Members Up refactoring moves the printMeeting() meeting from AccountingDepartment to its superclass Department.

class Department { name; printName() { console.log("Department name: " + this.name); } printMeeting() { console.log("The Accounting Department meets each Monday at 10am."); } } class AccountingDepartment extends Department { generateReports() { console.log("Generating accounting reports..."); } }

To move the methods of a class to a superclass

  1. Place the cursor anywhere inside the class from which you want to pull the members up.
  2. Choose Refactor | Pull Members Up on the main menu or on the context menu. The Pull Members Up dialog opens.
  3. From the drop-down list, choose the superclass where you want to move the methods.
  4. To pull a method up, select the checkbox next to it in the Members to be pulled up list.

Rename refactorings

Besides Renaming files and folders, which is available in the context of any language, you can also rename classes, functions, variables, and parameters. JetBrains Rider changes the name of the symbol in its declaration and by default all its usages in the current project.

To rename a function, a class, or a variable

  1. In the editor, select the symbol to rename and press Ctrl+R, R or choose Refactor | Rename on the context menu or on the main menu.
  2. In the Rename dialog that opens, type the new name of the symbol.
  3. Optionally, select the Search in comments and strings and Search for text occurrences checkboxes to rename the usages of the function or the class in comments, string literals, and text.
  4. If necessary, preview and apply the changes.

To rename a parameter

  1. Select the parameter in the editor and press Ctrl+R, R or choose Refactor | Rename on the context menu or on the main menu.
  2. In the text box with red canvas around the selected parameter, type the new parameter name.
  3. Press Enter to run the refactoring.

Keeping the names of classes and containing files in compliance

When you rename a class, JetBrains Rider also suggests renaming the file if it has the same name. If you accept the suggestion, JetBrains Rider updates the name of this file in import statements in other files.

If you reject this suggestion, you can rename the file at any time later using the Rename file... intention action. Another intention action suggests moving the class to a new file with the corresponding name. The format of the suggested name is determined by the style chosen from the the Filename convention list on the Code Style: JavaScript page.

ws_js_refactoring_rename_file_intention_custom_naming_convention.png

Extract refactorings

JetBrains Rider provides various Extract refactorings to introduce parameters, variables, constants, fields, methods, and functions. To run any of these refactorings, select the expression to refactor and choose Refactor | Extract | <target>. You can select an entire expression or place the cursor anywhere inside it and JetBrains Rider will help you with the selection.

Extract Parameter

Use the Extract Parameter refactoring to replace an expression in the calls of a function with a parameter. JetBrains Rider will update the declaration and the calls of the function accordingly. The default value of the new parameter can be initialized inside the function body or passed through function calls.

Suppose you have a piece of code with a hardcoded 1 in the function calculate_sum(i). With the Extract Parameter refactoring, you can replace this hardcoded 1 with a i2 parameter. The new i2 parameter can be extracted as optional or as required.

Example 1: Extracting an optional parameter
A new parameter i2 is extracted as an optional parameter. The new parameter is initialized in the body of calculate_sum(i) and the call of calculate_sum(i) in show_sum() is not changed.

function calculate_sum(i) { alert('Adding ' + 1 + ' to ' + i); return 1 + i; } function show_sum() { alert('Result: ' + calculate_sum(5)); }
function calculate_sum(i, i2) { i2 = i2 || 1; alert('Adding ' + i2 + ' to ' + i); return i2 + i; } function show_sum() { alert('Result: ' + calculate_sum(5)); }

Example 2: Extracting a required parameter
A new parameter i2 is extracted as a required parameter, the call of calculate_sum(i) in show_sum() is changed accordingly.

function calculate_sum(i) { alert('Adding ' + 1 + ' to ' + i); return 1 + i; } function show_sum() { alert('Result: ' + calculate_sum(5)); }
function calculate_sum(i, i2) { alert('Adding ' + i2 + ' to ' + i); return i2 + i; } function show_sum() { alert('Result: ' + calculate_sum(5, 1)); }

To extract a parameter

  1. In the editor, place the cursor within the expression that you want to convert into a parameter and press Ctrl+R, P or choose Refactor | Extract | Parameter on the context menu or on the main menu.
  2. If several expressions are detected in the current cursor location, select the required one in the Expressions list.
    ws_js_extract_parameter_select_expression.png
  3. If more than one occurrence of the selected expression is found, choose Replace this occurrence only or Replace all occurrences in the Multiple occurrences found pop-up menu.
    ws_js_extract_parameter_multiple_occurrences.png
    Finally, the pop-up window for configuring the refactoring appears.
    ws_js_extract_parameter_specify_parameter_name_and_type.png
  4. Select the Generate JSDoc to have a JSDoc comment block generated. This may be helpful if you need to specify a custom default parameter value. Learn more from the JSDoc Official website.
  5. Choose the type of the new parameter (optional or required) and specify its default value, if applicable:
    • If the Optional parameter checkbox is selected, the parameter will be initialized with the default value in the function body.
    • If the Optional parameter checkbox is cleared, the default parameter value will be passed through the existing function calls. All the function calls will change according to the new function signature and a parameter initialization will be added to the function body.
    Initially, JetBrains Rider accepts the expression where the refactoring is invoked as the default value. In most cases you do not need to change it. If it is still necessary, specify another default value in the JSDoc comment in the format @param <parameter name> - <default value>.
  6. Accept one of the suggested parameter names by double-clicking it in the pop-up list or specify a custom name in the text box with red canvas. Press Enter when ready.
    ws_js_extract_parameter_result.png
    Also note that in the ES6 code, the new default function parameter syntax function calculate_sum(i, i2 = 1) will be applied instead of i2 = i2 || 1;. Learn more about default function parameters from the https://developer.mozilla.org website.

Choosing the refactoring mode

You can extract a parameter right in the editor (in the in-place mode) as described above or use the Extract Parameter dialog. These two approaches are rather similar, the difference is as follows:

  • Previewing the results of the refactoring.
    In the dialog box, you can click Preview and examine the expected changes in the dedicated tab of the Find tool window. In the in-place mode, this functionality is not available.
  • Specifying the default parameter value.
    In the dialog box, JetBrains Rider suggests the default parameter value in the Value field where you can accept the suggestion or specify another value. In the in-place mode, JetBrains Rider treats the expression where the refactoring is invoked as the default parameter value. To specify another value, you have to use a JSDoc comment block.

By default, JetBrains Rider runs the Extract Parameter refactoring in the in-place mode. To use the Extract Parameter dialog box, In the Settings/Preferences dialog (Ctrl+Alt+S), click Editor | General. On the General page that opens, clear the Enable in-place mode checkbox in the Refactorings area.

Extract Variable

Use the Extract Variable refactoring to replace an expression with a function-scoped variable (var), a block-scoped variable (let), or a constant. This refactoring makes your source code easier to read and maintain. It also helps you avoid using hardcoded constants without any explanations about their values or purposes.

Suppose you have a function with a partially hardcoded expression in the return statement:

Parenizor.method('toString', function ()) { return '(' + this.getValue() + ')'; }
With the Extract Variable refactoring, you can replace the '(' + this.getValue() + ')' expression with a variable, for example, string. The scope of the extracted variable depends on the statement used in its declaration (var or let) and the context in which the new variable is declared (inside or outside a function).

Example 1: Extracting a block-scoped variable with a let statement declaration
A variable string is extracted from the '(' + this.getValue() + ')' expression in the return statement. The new variable is declared with a let statement inside Parenizor.method('toString', function ()).

Parenizor.method('toString', function ()) { return '(' + this.getValue() + ')'; }
Parenizor.method('toString', function ()) { let string = '(' + this.getValue() + ')'; return string; }

Example 2: Extracting a variable and declaring it outside any function
A variable appName is extracted from the navigator.appName expression and declared with a var statement outside any function.

var browserName = "N/A"; if (navigator.appName.indexOf("Netscape") != -1) { browserName = "NS"; } else if (navigator.appName.indexOf("Microsoft") != -1) { browserName = "MSIE"; } else if (navigator.appName.indexOf("Opera") != -1) { browserName = "O"; }
var browserName = "N/A"; var appName = navigator.appName; if (appName.indexOf("Netscape") != -1) { browserName = "NS"; } else if (appName.indexOf("Microsoft") != -1) { browserName = "MSIE"; } else if (appName.indexOf("Opera") != -1) { browserName = "O"; }

To extract a variable

  1. In the editor, select the expression to convert into a variable and press Ctrl+R, V or choose Refactor | Extract | Variable on the context menu or on the main menu.
  2. If several expressions are detected in the current cursor location, select the required one in the Expressions list.
    ws_js_refactoring_extract_variable_inplace_select_expression.png
  3. If more than one occurrence of the selected expression is found, choose Replace this occurrence only or Replace all occurrences in the Multiple occurrences found pop-up menu.
    ws_js_refactoring_extract_variable_inplace_multiple_occurrences.png
    Finally, the pop-up window for configuring the refactoring appears.
  4. In the pop-up menu, choose the statement to use in the declaration of the new variable:
    ws_js_refactoring_extract_variable_inplace_choose_scope_type.png
  5. Accept one of the suggested variable names by double-clicking it in the pop-up list or specify a custom name in the text box. Press Enter when ready.

Choosing the refactoring mode

You can extract a variable right in the editor (in the in-place mode) as described above or use the Extract Variable dialog. By default, JetBrains Rider runs the Extract Variable refactoring in the in-place mode. To use the Extract Variable dialog box, In the Settings/Preferences dialog (Ctrl+Alt+S), click Editor | General. On the General page that opens, clear the Enable in-place mode checkbox in the Refactorings area.

Extract Field

The Extract Field refactoring declares a new field and initializes it with the selected expression. The original expression is replaced with the usage of the field.

In the examples below, the same field, _calcArea, is extracted. The examples illustrate three different ways to initialize the extracted field.

Example 1: The extracted field is initialized in the enclosing method

class Rectangle { constructor(height, width) { this.height = height; this.width = width; } get area() { return this.calcArea(); } calcArea() { return this.height * this.width; } }
class Rectangle { constructor(height, width) { this.height = height; this.width = width; } _calcArea; get area() { this._calcArea = this.calcArea(); return this._calcArea; } calcArea() { return this.height * this.width; } }

Example 2: The extracted field is initialized in its declaration

class Rectangle { constructor(height, width) { this.height = height; this.width = width; } get area() { return this.calcArea(); } calcArea() { return this.height * this.width; } }
class Rectangle { constructor(height, width) { this.height = height; this.width = width; } _calcArea = this.calcArea(); get area() { return this._calcArea; } calcArea() { return this.height * this.width; } }

Example 3: The extracted field is initialized in the constructor of the class

class Rectangle { constructor(height, width) { this.height = height; this.width = width; } get area() { return this.calcArea(); } calcArea() { return this.height * this.width; } }
class Rectangle { constructor(height, width) { this._calcArea = this.calcArea(); this.height = height; this.width = width; } _calcArea; get area() { return this._calcArea; } calcArea() { return this.height * this.width; } }

To extract a field

  1. In the editor, select the expression to convert into a field and press Ctrl+R, F or choose Refactor | Extract | Field on the context menu or on the main menu.
  2. Accept one of the suggested names from the list or type a custom one.
  3. Choose where the new field will be initialized:
    ws_js_extract_field_dialog_1.png

Extract Method

The Extract Method refactoring lets you create a named method or function with the extracted code. When the Extract Method refactoring is invoked, JetBrains Rider detects the variables that are the input for the selected code fragment and the variable that is the output for it. The detected output variable is used as the return value for the extracted method or function.

In the examples below, a function is extracted from the c = a + b; expression.

Example 1: Extracting a globally scoped function from an expression inside another function
The c = a + b; expression, where the refactoring is invoked, is inside the MyFunction() function. The global destination scope is chosen.

Example 1.1: A function declaration is generated

function MyFunction(a,b) { c = a + b; return (c * c); } result = MyFunction(4,6); document.write(result);
function extracted(a, b) { c = a + b; } function MyFunction(a,b) { extracted(a, b); return (c * c); } result = MyFunction(4,6); document.write(result);

Example 1.2: The extracted function is declared inside an expression

function MyFunction(a,b) { c = a + b; return (c * c); } result = MyFunction(4,6); document.write(result);
let extracted = function (a, b) { c = a + b; }; function MyFunction(a,b) { extracted(a, b); return (c * c); } result = MyFunction(4,6); document.write(result);

Example 2: Extracting a globally scoped function from an expression outside any function
The c = a + b; expression, where the refactoring is invoked, is outside any function. Therefore no choice of the destination scope is available.

Example 2.1: A function declaration is generated

c = a + b;
function extracted() { c = a + b; } extracted();

Example 2.2: The extracted function is declared inside an expression

c = a + b;
let extracted = function () { c = a + b; }; extracted();

Example 3: Extracting a function with a definition inside the enclosing function
The c = a + b; expression, where the refactoring is invoked, is inside the MyFunction() function. The function MyFunction destination scope is chosen.

function MyFunction(a,b) { c = a + b; return (c * c); } result = MyFunction(4,6); document.write(result);
function MyFunction(a,b) { function extracted() { c = a + b; } extracted(); return (c * c); } result = MyFunction(4,6); document.write(result);

To extract a function

  1. In the editor, select a code fragment to convert into a function and press Ctrl+R, M or choose Refactor | Extract | Method on the context menu or on the main menu.
  2. If the selected expression is inside a function, choose the destination scope from the pop-up list:
    • If you choose global, the extracted function will be declared outside any function. See Example 1 above.
    • To define the extracted function inside the current enclosing function, choose function <current enclosing function name>. See Example 3 above.
  3. To open the Extract Function dialog with more options, press Ctrl+R, M once again. In this dialog, you can choose whether the extracted function will be declared through a generated function declaration or inside an expression. See Examples above.

To open the Extract Function dialog by default

  • In the Settings/Preferences dialog (Ctrl+Alt+S), click Editor | General. On the General page that opens, clear the Enable in-place mode checkbox in the Refactorings area.

Extract Superclass

The Extract Superclass refactoring creates a new abstract class based on the members of the current class. The created class is extended automatically.

Suppose you have a class AccountingDepartment and you expect that the printName() method from it will be re-used.

class AccountingDepartment { name; printName() { console.log("Department name: " + this.name); } printMeeting() { console.log("The Accounting Department meets each Monday at 10am."); } generateReports() { console.log("Generating accounting reports..."); } }
You can extract a superclass Department and include the printName and the Name field in it.
class Department { name; printName() { console.log("Department name: " + this.name); } } class AccountingDepartment extends Department { printMeeting() { console.log("The Accounting Department meets each Monday at 10am."); } generateReports() { console.log("Generating accounting reports..."); } }

To extract a superclass

  1. Place the cursor anywhere inside the class from which you want to extract a superclass.
  2. Choose Refactor | Extract | Superclass on the main menu or on the context menu. The Extract Superclass dialog opens.
  3. Specify the name of the new superclass and select the checkboxes next to the class members you want to include in it. Optionally, mark the members that you want to make abstract.
  4. In the Destination file field, specify the location of the file where the new class will be. By default, the field shows the path to the current file where the refactoring was invoked.
  5. Choose Extract Superclass. JetBrains Rider creates a new class and marks the source class with extends.
    To create a superclass and replace the references to the source class with references to the superclass in parameters of methods, choose Extract superclass and use it where possible. JetBrains Rider shows the proposed changes in the Refactoring Preview pane of the Find tool window.

Extract Vue Component

The Extract Vue Component refactoring lets you extract new Vue.js components from existing ones without any copying and pasting. Note that this refactoring works only in-place, so make sure the Enable in-place mode checkbox is selected on the Editor: General page.

To extract a Vue.js component

  1. Select the template fragment to extract and choose Refactor | Extract | Extract Vue Component on the main menu or on the context menu of the selection.
  2. Type the name of the new component. If this name is already used or invalid, JetBrains Rider shows a warning. Otherwise a new single-file component is created and imported into the parent component.

Inline refactorings

Inline refactorings are opposite to Extract refactorings.

Example 1: Inline Variable
The Inline Variable refactoring replaces a redundant usage of a variable or a constant with its initializer. This type of refactoring is available only for block-scoped and function-scoped variables.

Parenizor.method('toString', function () { var string = '(' + this.getValue() + ')'; return string; }
Parenizor.method('toString', function () { return '(' + this.getValue() + ')'; }

Example 2: Inline Function
The Inline Method/Inline Function refactoring results in placing the body of a method or a function into the body of its caller(s); the method/function itself is deleted.
In the example below, the body of Sum() is placed in the body of Multiplication() and Division().

function Sum(a, b) { return a + b; } function Multiplication(a, b) { c = Sum(a, b); d = c * c; return d; } function Division(a, b) { c = Sum(a, b); d = Multiplication(a, b); result = c / d; return result; }
function Multiplication(a, b) { c = a + b; d = c * c; return d; } function Division(a, b) { c = a + b; d = Multiplication(a, b); result = c / d; return result; }

To run an Inline refactoring

  • In the editor, place the cursor at the symbol to be inlined and press Ctrl+R, I or choose Refactor | Inline on the context menu or on the main menu.

Change Signature refactoring

Use the Change Signature refactoring to change the function name, to add, remove, reorder, and rename parameters, and to propagate new parameters through the hierarchy of calls.

The examples below show different ways to run the Change Signature refactoring. In all the cases, the function result() is renamed to generate_result() and a new parameter input is added to this function. The examples show how the function call, the calling function (show_result()), and other code fragments may be affected depending on the refactoring settings.

Example 1: Renaming a function, adding a parameter, and passing its value through the function call
In this example, the function result() is renamed to generate_result(), a parameter input is added, and the value 100 is passed as a parameter in the function call.

function result() { } function show_result() { alert('Result: ' + result()); }
function generate_result(input) { } function show_result() { alert('Result: ' + generate_result(100)); }

Example 2: Renaming a function and adding a default parameter
In this example, the function result() is renamed to generate_result(). A default parameter input is added with the value 100. The new parameter is initialized in the generate_result() in the format function generate_result(input = 100) {} for ES6 language level or input = input || 100 for ES5.

function result() { } function show_result() { alert('Result: ' + result()); }
function generate_result(input = 100) { } function show_result() { alert('Result: ' + generate_result()); }

Example 3: Renaming a function, adding a default parameter, and propagating the parameter to the function call
In this example, the function result() is renamed to generate_result(). A default parameter input is added with the value 100. The new parameter is initialized in the generate_result() in the format function generate_result(input = 100) {} for ES6 language level or input = input || 100 for ES5. The input parameter is propagated through the calling function show_result() so the function call is changed accordingly.

function result() { } function show_result() { alert('Result: ' + result()); }
function generate_result(input = 100) { } function show_result() { alert('Result: ' + generate_result()); }

To invoke Change Signature

  • In the editor, place the cursor within the name of the function to refactor and press Ctrl+R, S or choose Refactor | Change Signature on the context menu or on the main menu. The Change Signature dialog opens.

To rename a function

  • In the Change Signature dialog (Ctrl+R, S), edit the Name field.

To manage the function parameters

  • In the Change Signature dialog (Ctrl+R, S), use the table of parameters and the buttons to the right of it:
    • To add a new parameter, click new (Ctrl+N) and specify the name of the new parameter and its default value or the value to be passed through function calls.
    • To remove a parameter, click any of the cells in the corresponding row and click delete (Ctrl+R, D).
    • To reorder the parameters, use arrowUp (Alt+Up) and arrowDown (Alt+Down).
    • To rename a parameter, edit the Name field.
    • If necessary, propagate the new parameter to the functions that call the current function.

To propagate a parameter along the hierarchy of calls

  1. In the Change Signature dialog (Ctrl+R, S), select the parameter and click propagateParameters. The Select Methods to Propagate New Parameters dialog opens. The left-hand pane shows the hierarchy of function calls. When you select a function, the right-hand pane shows its code and the code of the function it calls in the Caller Method and Callee Method fields respectively.
  2. In the left-hand pane, select the checkboxes next to the functions where you want to propagate the parameter and click OK.

To preview the changes and complete the refactoring

  1. In the Change Signature dialog (Ctrl+R, S), click Preview.
  2. In the Refactoring Preview tab of the Find tool window, view the expected changes, make the necessary adjustments, and click Do Refactor when ready.
Last modified: 20 August 2018