Skip to content

Instantly share code, notes, and snippets.

@milichev
Created December 27, 2018 01:21
Show Gist options
  • Save milichev/857c54be6a55298fc8b9497ebcf1de9f to your computer and use it in GitHub Desktop.
Save milichev/857c54be6a55298fc8b9497ebcf1de9f to your computer and use it in GitHub Desktop.
Traverses .ts source files in a project and replaces all absolute imports with aliases to relative ones, according to paths in tsconfig.json
const fs = require("fs");
const path = require("path");
const globby = require("globby");
const srcPath = fn("../src");
const aliases = getAliases();
(async () => {
const files = await findFiles();
files
.forEach(async (fn, i) => {
console.debug(i, "[processing]", fn);
const fullFn = path.join(srcPath, fn);
let text = fs.readFileSync(fullFn, "utf8");
text = await replaceAliases(text, fn);
fs.writeFileSync(fullFn, text, { encoding: "utf8" });
});
})();
// console.log(aliases);
const catchImportFrom = /\sfrom\s+\'(\.[a-z]+\/?)([^']+)?\';/g;
async function replaceAliases(text, fn) {
const fullFn = path.join(srcPath, fn);
return text.replace(
catchImportFrom,
(match, alias, rest) => {
// console.log(match, alias, rest);
const target = aliases[alias];
if (!target) {
return match;
}
const abs = path.join(target, rest || "");
let rel = path
.relative(
path.dirname(fullFn),
abs
)
.replace(/\\/g, "/");
if (!rel.startsWith(".")) {
rel = `./${rel}`;
}
return ` from '${rel}';`;
}
);
}
async function findFiles() {
const tsFiles = await globby(
["**/?(*.){js,jsx,mjs,ts,tsx}", "!**/*.d.ts"],
{ cwd: srcPath }
);
// tsFiles.forEach((f, i) => console.log(i, f))
return tsFiles;
// .map(fn => path.join(srcPath, fn))
// .slice(108, 109);
}
function fn(target) {
return path.resolve(__dirname, target);
}
// fs.readFileSync
function getAliases() {
const tsconfig = require(fn("../tsconfig.json"));
const { paths } = tsconfig.compilerOptions;
return Object.keys(paths)
.reduce(
(acc, k) => {
const starts = k.endsWith("*") ? k.slice(0, -1) : k;
const path0 = paths[k][0];
const target = path.resolve(
srcPath,
path0.endsWith("*") ? path0.slice(0, -1) : path0
);
acc[starts] = target;
return acc;
},
{}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment