Simon Vetter
Simon Vetter's Blog

Simon Vetter's Blog

Recursive regex replace in VSCode

Convert named imports to default imports from node modules

Simon Vetter's photo
Simon Vetter
ยทOct 28, 2021ยท

1 min read

I wanted to make all imports to mui use direct links to the component, to speed upd bundling and improv development recompile speed. Therefore I tried to do it within vscode with regular expression, and i Came up with the following regular exression and replace code

import[\s\n]*\{[\s\n]*((\w+),?[\s\n])*\}[\s\n]*from "@mui/material"
import $2 from "@mui/material/$2"

However, this only works if only one this was importet. So I need somme way to replace the repeated part of the regular exression. This however is not possible to my knowledge. But no worries there is a funny workaround. Instead of replacing all in one stepp I can build a recursive replace algorithm that only transforms the first import to what I actually want, and converts the rest to an old import that will be matched again, as long as it has any imports in it.

import[\s\n]*\{[\s\n]*(\w+)[\s\n,]*([\s\n\w,]+)\}[\s\n]*from "@mui/material"
import $1 from "@mui/material/$1"
import { $2 } from "@mui/material"

image.png

image.png

image.png

image.png

The only problem left is a bunch of empty imports but they are easy to clean up

import[\s\n]*\{[\s\n]*\}[\s\n]*from "@mui/material"

This regex does the trick. So after about 25 runs all imports are refactored ๐Ÿ‘

ย 
Share this