javascript - 正则表达式匹配将 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*
你能帮我解决这个问题吗?
解决方案
您可以分两步完成(这和我的 regex-fu 一样好)。
步骤1:
(import \{ )?((\w+)[, ]+)(?=.*?(\} from '(.*)'))
搜索正则表达式
import { $3 } from '$5/lib/$3'\n
查找正则表达式
} 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 ""
推荐阅读
- html - 如何在不安装插件的情况下为 wordpress 表格添加边框?
- perl - 从 golang 运行 perl
- css - 强制滚动条在 iphone Chrome (CSS) 上始终可见
- android - 如何在没有 Transformations.map 的 ViewModel 中初始化 LiveData?
- python - 在线程中创建的 DatabaseWrapper 对象只能在同一线程中使用。”尝试使用 celery 插入数据库时
- amazon-web-services - AWS Lambda 如何收费?
- sql - 访问子查询连接
- apache-spark - pypark 替换列值
- database - SQL:当一列有多个类别时如何设计数据库?
- oracle - Oracle SQL 错误:ORA-00955:名称已被现有对象使用