Created
April 16, 2018 12:38
-
-
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
This file contains 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
Probably eslint plugin can help someone solve this problem faster. Link -> https://github.com/qDanik/eslint-plugin-path