Created
October 9, 2023 09:57
-
-
Save heycqing/09862d9695b35b80bf039045c15164cf to your computer and use it in GitHub Desktop.
require to import
This file contains hidden or 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
| const fs = require('fs'); | |
| const path = require('path'); | |
| const directoryPath = './your_directory_path'; | |
| function replaceRequiresWithImports(directoryPath) { | |
| fs.readdir(directoryPath, (err, files) => { | |
| if (err) { | |
| console.error('Error reading directory:', err); | |
| return; | |
| } | |
| files.forEach((file) => { | |
| const filePath = path.join(directoryPath, file); | |
| fs.stat(filePath, (err, stats) => { | |
| if (err) { | |
| console.error('Error getting file stats:', err); | |
| return; | |
| } | |
| if (stats.isFile() && file.endsWith('.js')) { | |
| replaceFileRequiresWithImports(filePath); | |
| } else if (stats.isDirectory()) { | |
| replaceRequiresWithImports(filePath); | |
| } | |
| }); | |
| }); | |
| }); | |
| } | |
| function replaceFileRequiresWithImports(filePath) { | |
| fs.readFile(filePath, 'utf8', (err, data) => { | |
| if (err) { | |
| console.error('Error reading file:', err); | |
| return; | |
| } | |
| const replacedData = data.replace(/const (\w+) = require\(['"]([^'"]+)['"]\)/g, "import $1 from '$2'"); | |
| if (replacedData !== data) { | |
| fs.writeFile(filePath, replacedData, 'utf8', (err) => { | |
| if (err) { | |
| console.error('Error writing file:', err); | |
| } else { | |
| console.log(`Replaced requires with imports in file: ${filePath}`); | |
| } | |
| }); | |
| } | |
| }); | |
| } | |
| replaceRequiresWithImports(directoryPath); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment