Skip to content

Instantly share code, notes, and snippets.

@teimurjan
Created March 30, 2020 08:07
Show Gist options
  • Select an option

  • Save teimurjan/3fa0f1029ee89cd523f4c299fd01dedf to your computer and use it in GitHub Desktop.

Select an option

Save teimurjan/3fa0f1029ee89cd523f4c299fd01dedf to your computer and use it in GitHub Desktop.

Revisions

  1. teimurjan created this gist Mar 30, 2020.
    78 changes: 78 additions & 0 deletions replaceImports.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,78 @@
    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;
    });