Skip to content

Instantly share code, notes, and snippets.

@phenax
Created April 16, 2018 12:38
Show Gist options
  • Save phenax/468db4019d6958f939fa8694e53ad32a to your computer and use it in GitHub Desktop.
Save phenax/468db4019d6958f939fa8694e53ad32a to your computer and use it in GitHub Desktop.
Codemod transform to convert all relative paths to absolute import paths inside src
const path = require('path');
const SOURCE = 'src';
const SOURCE_PATH = path.resolve(SOURCE) + '/';
const removeSourceDirName = path =>
path.replace(new RegExp(`^${SOURCE}\/?`, 'gi'), '');
const getAbsolutePath = (importPath, filePath) => {
return path.resolve(path.dirname(filePath), importPath)
.replace(SOURCE_PATH, '');
};
const replaceImportPath = (j, node, filePath) => j.importDeclaration(
node.value.specifiers,
j.literal(getAbsolutePath(node.value.source.value, filePath))
);
export default function(file, api) {
const j = api.jscodeshift;
const filePath = file.path;
return j(file.source)
.find(j.ImportDeclaration)
.replaceWith(node => replaceImportPath(j, node, filePath))
.toSource();
};
@qdanik
Copy link

qdanik commented Dec 17, 2022

Probably eslint plugin can help someone solve this problem faster. Link -> https://github.com/qDanik/eslint-plugin-path

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment