Skip to content

Instantly share code, notes, and snippets.

@elderbas
Created May 5, 2021 21:15
Show Gist options
  • Save elderbas/bb4131fa60340feaef82b53681c9a896 to your computer and use it in GitHub Desktop.
Save elderbas/bb4131fa60340feaef82b53681c9a896 to your computer and use it in GitHub Desktop.
codemod script to remove useEffect if it's not being used
module.exports = function (file, api) {
const j = api.jscodeshift;
const { CallExpression, Identifier } = j;
return getReactImportStatementNode()
.forEach((node, index) => {
node.value.specifiers.forEach((specifier, index) => {
if (specifier.local.name === "useEffect") {
if (!shouldKeepUseEffectImport()) {
delete node.value.specifiers[index];
}
}
});
})
.toSource();
function shouldKeepUseEffectImport() {
return (
j(file.source)
.find(j.CallExpression)
.filter((node, index) => {
return node.value.callee.name === "useEffect";
})
.size() > 0
);
}
function getReactImportStatementNode() {
return j(file.source)
.find(j.ImportDeclaration) // where it's from 'react'
.filter((node, index) => {
return node.value.source.value === "react";
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment