简体   繁体   中英

With regex find and replace all require imports with ES import?

In VS Code I want to replace all my imports using require and update the import path...

import myImport = require("path/of/import");

to this

import myImport from "path/of/import";

Essentially...

Remove the require(" ... ") to replace with from "" syntax.

I've tried some tools and extensions in VS code, but they don't seem to work...so wanted to try just Regex.

I'm not sure if this is what you are looking for, but how about matching for the below:

import (\w+) = require\((.*?)\);?

… and replacing with the below:

import \1 from \2;


Demo:
https://regex101.com/r/gcVbPN/1

 const regex = /import (\w+) = require\((.*?)\);?/; const substitution = 'import $1 from $2;'; const before = 'import myImport = require("path/of/import");' const after = before.replace(regex, substitution); console.log(`${before}\n${after}`);

Are you trying to permanently change the import? As in, you now want your imports to be import MyImport from "path/of/import"; and you don't need import myImport = require("path/of/import"); ? If so, you could likely use VS Code's Search tool (ctrl+shift+F), where you can search for a string of text and replace them across the entirety of the directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM