Search code examples
regexvisual-studio-coderequirejses6-modules

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.


Solution

  • 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}`);