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.
CodePudding user response:
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}`);
CodePudding user response:
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.