Skip to content

Instantly share code, notes, and snippets.

@rleroi
Last active March 9, 2022 11:17
Show Gist options
  • Save rleroi/53e0dc265f0b860567354326d8e2b560 to your computer and use it in GitHub Desktop.
Save rleroi/53e0dc265f0b860567354326d8e2b560 to your computer and use it in GitHub Desktop.
Replaces all inline `require('path').default` with `import Name from 'path'`
/*
* Replaces all inline `require('path').default` with `import Name from 'path'`
* Adding them as imports to the top of the file.
* Usage: node RequireToImport.js dir [dry]
*/
const glob = require("glob")
const path = require('path');
const fs = require('fs');
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
(function main() {
const dirName = process.argv[2];
if(!dirName) {
return console.error('Usage: node RequireToImport.js dir [dry]');
}
const directoryPath = path.join(__dirname, dirName, '**', '*.js');
glob(directoryPath, {}, function (err, files) {
if (err) {
return console.log('Unable to scan directory: ' + err);
}
files.forEach(function (fileName) {
console.log(fileName);
fs.readFile(fileName, 'utf8' , (err, data) => {
if (err) {
return console.error(err)
}
let contentImports = '';
let content = data;
let matches = Array.from(data.matchAll(/require\('([^']+)\'\).default/g));
// remove duplicate requires
matches = matches.filter((value, index, self) => {
return self.findIndex(v => v[0] === value[0]) === index;
});
for (const match of matches) {
const importPath = match[1];
const importName = path.basename(importPath);
contentImports += `import ${importName} from '${importPath}'\n`;
const oldImport = match[0];
content = content.replace(new RegExp(escapeRegExp(oldImport), 'g'), importName);
}
content = contentImports + "\n\n" + content;
if (process.argv[3]) {
console.log(fileName + ":\n\n" + content + "\n\n");
} else {
// replace content of fileName
fs.writeFile(fileName, content, err => {
if (err) {
return console.error(err);
}
})
}
})
});
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment