Regex matching to change ES module import to direct import

Viewed 816

I have a component library package and it's used in a lot of files like this:

import { Grid, Heading, Button } from 'component-library'

I want to change all of my import to something like this:

import { Grid } from 'component-library/lib/Grid'
import { Heading } from 'component-library/lib/Heading'
import { Button } from 'component-library/lib/Button'

I found an extension on VSCode for doing this:
https://marketplace.visualstudio.com/items?itemName=angelomollame.batch-replacer&ssr=false#overview

And it seems it's accepting regex too. I tried to write a regex to find a replace old imports to a new one but my regex not working. This is my current regex:

(?:import)\s+([\w,{}\s\*]+)\s+(?:from)?\s*(?:["'])?([@\w\s\\\/.-]+)(?:["'])?\s*

Can you help me to fix this?

2 Answers

You can do it in two steps (that'as good as my regex-fu can do).

Step 1:

(import \{ )?((\w+)[, ]+)(?=.*?(\} from '(.*)')) Search regex

import { $3 } from '$5/lib/$3'\n Find regex

Regex101


This leaves one stray } from 'great-library'; behind for each original import line (maybe someone can improve the regex to avoid that), so remove it with:

^\} from.*$ Search

Replace with nothing.


There are a few multi-regex replace extensions out there where you can combine these two steps into one. For example, using Batch Replacer try this "script":

replace-regex "(import { )?((\w+)[, ]+)(?=.*?(} from '(.*)'))"
with "import { $3 } from '$5/lib/$3'\n"

replace-regex "(?<!.)} from.*\r?\n?"
with ""

Batch Replacer demo

Without any extensions, just use regular expression as many times as there is a match:

Find:

(import\s*{\s*)(\w+)\s*,([\w\s,*]+?)(\s*}(?:\s*from)?\s*)(["'])?([@\w\s\\/.-]*?)\5

Replace:

$1$2$4$5$6$5\n$1$3$4$5$6$5

See the regex demo

The pattern will match and capture parts of the pattern into separate groups. Only the first word in the round brackets will be captured each time and a line with just that word will be output + a newline and a line containing other words inside the brackets.

That is why you need to run search and replace until no matches are found.

Related