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 FileSettingsEditorInspections. Activate GeneralStructural 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”.

Structural search and replace template
Structural search and replace template

Open the “Edit variables” dialog and use the following occurrences count:

  • functionName: 1,1
  • parameterNames: 1,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