Darek Kay's picture
Darek Kay
Solving web mysteries

Convert to arrow function in WebStorm

Since version 2019, WebStorm has a built-in "convert to variable holding arrow function" suggestion, making this method obsolete. However, you may still find this article useful for other replacements.

Since ECMAScript 2015, I prefer using arrow functions over regular functions in most situations. Arrow functions are more concise (when used inline), and they inherit this from the enclosing scope, making it less confusing. It doesn't take long to manually rewrite a function into an arrow function, but it can be automated.

Structural Search and Replace is one of the more powerful features of IntelliJ IDEA and other JetBrains IDEs. It allows us to replace code for a certain scope or the whole project, taking advantage of the IDE's awareness of the syntax of the supported language. When combined with custom inspections, WebStorm is able to suggest an intention action when a conversion is possible:

Intention action
Intention action

For inline functions, a "Convert to arrow function" intention is already predefined. However, it's not available for regular function definitions. Here's a step-by-step guide to set this up. For a quick solution, feel free to go straight for my config file.

Setup

First, go to "File""Settings""Editor""Inspections". Activate "General""Structural Search Inspection" and change the severity to "No highlighting, only fix":

Structural search inspection
Structural search inspection

Now, let's define a search and replace template. Click the "+" button under options, select "Add Replace template" and use the following patterns:

  • Search template:
function $functionName$ ( $parameterNames$ ) {
  $content$
}
  • Replacement template:
const $functionName$ = ( $parameterNames$ ) => {
  $content$
};

Don't forget to set the file type to "JavaScript". Then, define the variables by clicking the variable name in the editor and selecting "Edit filters":

Structural search and replace template
Structural search and replace template

Use the following values:

  • functionName: 1,1 (default, hence optional)
  • parameterNames: 0,unlimited
  • content: 1,unlimited

Note: You'll need at least WebStorm / IntelliJ IDEA 2018.1 for this feature to work for multiline JS functions because of a bug in previous versions.

Finally, save the template as "Convert to arrow function". Now, when you place the cursor within a function, press Alt + Return to invoke intentions and select "Replace with ...".


Related posts

Convert to arrow function in WebStorm