Skip to content

Instantly share code, notes, and snippets.

@zhirzh
Last active August 1, 2019 09:25
Show Gist options
  • Save zhirzh/61c1983c3a69439a6c08fb6ff7888a11 to your computer and use it in GitHub Desktop.
Save zhirzh/61c1983c3a69439a6c08fb6ff7888a11 to your computer and use it in GitHub Desktop.
jscodeshift \
-t js-codemod-import-absolute-develop/import-absolute.js \
--extensions=ts,tsx \
--parser=tsx \
--sort=false \
--replace="$PWD/src/" \
--replaceWith="~" \
src/
import path from "path";
export default (file, { j }) => {
const root = j(file.source);
const imports = root.find(j.ImportDeclaration);
const projectpath = "/Users/zhirzh/Desktop/work/anarock.agents-app/";
const filepath = path.dirname(projectpath + file.path);
const newImports = imports.nodes().map(x => {
const importValue = x.source.value;
if (importValue.startsWith("~")) {
const modpath = importValue.replace("~", projectpath + "src/");
let newImportValue = path.relative(filepath, modpath);
if (/^\w/.test(newImportValue)) {
newImportValue = "./" + newImportValue;
}
if (
newImportValue.match(/\//g).length <= importValue.match(/\//g).length
) {
x.source.value = newImportValue;
}
}
return x;
});
j(imports.at(0).get()).insertBefore(newImports);
imports.remove();
return root.toSource();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment