首页 > 解决方案 > 正则表达式匹配将 ES 模块导入更改为直接导入

问题描述

我有一个组件库包,它在很多文件中使用,如下所示:

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

我想将我的所有导入更改为以下内容:

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

我在 VSCode 上找到了一个这样做的扩展:
https ://marketplace.visualstudio.com/items?itemName=angelomollame.batch-replacer&ssr=false#overview

它似乎也接受了正则表达式。我试图编写一个正则表达式来查找将旧导入替换为新的,但我的正则表达式不起作用。这是我当前的正则表达式:

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

你能帮我解决这个问题吗?

标签: javascriptregexvisual-studio-coderegex-groupregexp-replace

解决方案


您可以分两步完成(这和我的 regex-fu 一样好)。

步骤1:

(import \{ )?((\w+)[, ]+)(?=.*?(\} from '(.*)')) 搜索正则表达式

import { $3 } from '$5/lib/$3'\n 查找正则表达式

正则表达式101


} from 'great-library';这会为每个原始行留下一个流浪者import(也许有人可以改进正则表达式来避免这种情况),因此将其删除:

^\} from.*$ 搜索

什么都换。


有一些多正则表达式替换扩展,您可以将这两个步骤合二为一。例如,使用Batch Replacer试试这个“脚本”:

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

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

批量替换器演示


推荐阅读