Skip to content

Instantly share code, notes, and snippets.

@teimurjan
Created March 30, 2020 08:07
Show Gist options
  • Save teimurjan/3fa0f1029ee89cd523f4c299fd01dedf to your computer and use it in GitHub Desktop.
Save teimurjan/3fa0f1029ee89cd523f4c299fd01dedf to your computer and use it in GitHub Desktop.
Replace relative JS imports
var fs = require("fs");
var path = require("path");
const replaceImports = (pathToDir, replace) =>
fs.readdir(pathToDir, function(err, files) {
if (err) {
console.error("Could not list the directory.", err);
process.exit(1);
}
files.forEach(function(file, index) {
var pathToFile = path.join(pathToDir, file);
fs.stat(pathToFile, function(error, stat) {
if (error) {
console.error("Error stating file.", error);
return;
}
if (stat.isFile()) {
const newFileLines = fs
.readFileSync(pathToFile)
.toString()
.split("\n")
.map(function(line) {
if (line.startsWith("import ")) {
const importPath = line.match(/from ('|")(.*)('|")/);
if (importPath && importPath[2]) {
return replace({
line,
importPath: importPath[2],
pathToFile,
pathToDir
});
}
}
return line;
});
const newFileData = newFileLines.join("\n");
fs.writeFileSync(pathToFile, newFileData);
} else if (stat.isDirectory()) {
replaceImports(pathToFile, replace);
}
});
});
});
const rootPath = "/Users/xxx/Projects/xxx/web/src";
replaceImports(rootPath, ({ line, importPath, pathToFile, pathToDir }) => {
if (importPath.startsWith("../")) {
const depthSymbolMatch = importPath.match(/\.\.\//g);
if (depthSymbolMatch) {
const depth = depthSymbolMatch.length;
const pathToDirArr = pathToDir.split("/");
const absolutePrefix = pathToDirArr
.slice(0, pathToDirArr.length - depth)
.join("/");
const absolutePath =
"src" +
(absolutePrefix + "/" + importPath.replace(/\.\.\//g, "")).replace(
rootPath,
""
);
return line.replace(importPath, absolutePath);
}
} else if (importPath.startsWith("./")) {
const absolutePath =
"src" +
(pathToDir + "/" + importPath.replace(/\.\//g, "")).replace(rootPath, "");
return line.replace(importPath, absolutePath);
}
return line;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment