Last active
June 6, 2023 19:01
-
-
Save rubengmurray/0f9bf75bb1d917a4ec48dda5d3df722f to your computer and use it in GitHub Desktop.
Convert CommonJS to ESM imports with find + replace
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
In your preferred editor navigate to the search/find + replace section | |
- In find: `(?<='\.)(.*?)(?=')` | |
- In replace: `$1.js` | |
This will replace all imports beginning with `.`, ending with `'` to a `.js` file ending. | |
// It will not match these | |
import p from '@scoped/npm_package' | |
import p from 'npm_package' | |
// It will match these | |
import p from './local_file_import' | |
import p from '../../../local_file_import' | |
import p from '../../../local_file_import.js' | |
Note the last one: RegEx could be improved, but it would indicate conversion to ESM has already attempted. | |
This is designed for fresh migrations, and on repositories already using import/export pattern throughout code base. | |
*Be sure to exclude any file types you do not want to match (e.g. `*.json*, node_modules`)* | |
**You can test the RegEx here https://regex101.com/r/9cy4Sj/1** |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment