Last active
January 10, 2022 05:07
-
-
Save clodal/25849be71eb9215c25b24a89dbfe02ad to your computer and use it in GitHub Desktop.
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
/* eslint-disable */ | |
function isImport(node, imported) { | |
return node.type === "ImportDeclaration" && node.source.value === imported; | |
} | |
/** | |
* @usage Replace member imports from @mui/material with direct imports in `src` folder | |
* $ jscodeshift --extensions=js,jsx,ts,tsx --parser=tsx -t codemods/member-to-direct-import-codemod.js src --module '@mui/material' | |
* @param fileInfo | |
* @param j | |
* @param argOptions | |
* @returns {*} | |
*/ | |
module.exports = function(fileInfo, { jscodeshift: j }, argOptions) { | |
const moduleName = argOptions.module; | |
const ast = j(fileInfo.source); | |
// Methods relying on moduleName scope | |
function isModuleImport(node) { | |
return isImport(node, moduleName); | |
} | |
function transformImport(j) { | |
return ast => { | |
ast.node.source = j.literal(moduleName); | |
const imports = ast.value.specifiers; | |
j(ast).replaceWith(buildSplitImports(j, imports)); | |
}; | |
} | |
function buildSplitImports(j, imports) { | |
return imports.map(({ imported: { name } }) => { | |
return j.importDeclaration( | |
[j.importDefaultSpecifier(j.identifier(name))], | |
j.literal(`${moduleName}/${name}`) | |
); | |
}); | |
} | |
// Cache opening comments/position | |
const { comments, loc } = ast.find(j.Program).get("body", 0).node; | |
ast.find(j.ImportDeclaration, isModuleImport).forEach(transformImport(j)); | |
// Restore opening comments/position | |
Object.assign(ast.find(j.Program).get("body", 0).node, { comments, loc }); | |
return ast.toSource({ | |
arrowParensAlways: true, | |
quote: "single" | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment