Replacing CommonJS imports with ES-imports using the VSCode’s regex Replace

Airy
Jun 6, 2021

--

Time to time, I copy and paste code snippets from my old projects or from the Internet and imports in some of them turn out to be in CommonJS format (using require function). But what if my current project uses ES-style imports?

Thanks to regex support in VS Code’s search we can quickly replace most of them with their ES import equivalents using the following regex search string:

(const|var)(\s.*\s*)=\s*require\(((‘|”).*(‘|”))\)(;?)$

and the replacement string will be:

import$2from $3$6
The regular expression matched almost everything…
…and turned CommonJS into ES-imports

--

--