Forked from phenax/absolute-import-codemod-transform.js
Created
July 28, 2024 22:16
-
-
Save Oluwasetemi/0141064374d302c8a585f18315fde909 to your computer and use it in GitHub Desktop.
Codemod transform to convert all relative paths to absolute import paths inside src
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment