Forked from jaroslav-kubicek/codeshift-remove-alias.js
Created
February 10, 2022 01:29
-
-
Save fadi-george/4f1bf6e67dc625a82d84a2b209be8fbe to your computer and use it in GitHub Desktop.
Codeshift script to remove import alias
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"); | |
function replacePathAlias(currentFilePath, importPath, pathMap) { | |
// if windows env, convert backslashes to "/" first | |
console.log(currentFilePath) | |
currentFilePath = path.posix.join(...currentFilePath.split(path.sep)); | |
const regex = createRegex(pathMap); | |
return importPath.replace(regex, replacer); | |
function replacer(_, alias, rest) { | |
const mappedImportPath = pathMap[alias] + rest; | |
// use path.posix to also create foward slashes on windows environment | |
let mappedImportPathRelative = path.posix.relative( | |
path.dirname(currentFilePath), | |
mappedImportPath | |
); | |
// append "./" to make it a relative import path | |
if (!mappedImportPathRelative.startsWith("../")) { | |
mappedImportPathRelative = `./${mappedImportPathRelative}`; | |
} | |
logReplace(currentFilePath, mappedImportPathRelative); | |
return mappedImportPathRelative; | |
} | |
} | |
function createRegex(pathMap) { | |
const mapKeysStr = Object.keys(pathMap).reduce((acc, cur) => `${acc}|${cur}`); | |
const regexStr = `^(${mapKeysStr})(.*)$`; | |
return new RegExp(regexStr, "g"); | |
} | |
const log = true; | |
function logReplace(currentFilePath, mappedImportPathRelative) { | |
if (log) | |
console.log( | |
"current processed file:", | |
currentFilePath, | |
"; Mapped import path relative to current file:", | |
mappedImportPathRelative | |
); | |
} | |
const pathMapping = { | |
mmb: "./src/mmb" | |
}; | |
module.exports = pathMapping; | |
module.exports = function transform(file, api) { | |
const j = api.jscodeshift; | |
const root = j(file.source); | |
root.find(j.ImportDeclaration).forEach(replaceNodepathAliases); | |
root.find(j.ExportAllDeclaration).forEach(replaceNodepathAliases); | |
/** | |
* Filter out normal module exports, like export function foo(){ ...} | |
* Include export {a} from "mymodule" etc. | |
*/ | |
root | |
.find(j.ExportNamedDeclaration, node => node.source !== null) | |
.forEach(replaceNodepathAliases); | |
return root.toSource(); | |
function replaceNodepathAliases(impExpDeclNodePath) { | |
impExpDeclNodePath.value.source.value = replacePathAlias( | |
file.path, | |
impExpDeclNodePath.value.source.value, | |
pathMapping | |
); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update pathmapping then run like so
npx jscodeshift -t codeshift.js something/*