Skip to content

Instantly share code, notes, and snippets.

@mocanew
Last active February 9, 2022 12:02
Show Gist options
  • Select an option

  • Save mocanew/f2e147789cc1b67e855a20f35996c740 to your computer and use it in GitHub Desktop.

Select an option

Save mocanew/f2e147789cc1b67e855a20f35996c740 to your computer and use it in GitHub Desktop.
Simple codemod that replaces classnames npm module with the more performant yet very stable clsx
export default (fileInfo, api) => {
const j = api.jscodeshift;
const root = j(fileInfo.source);
// find import $x from 'classnames'
const importDeclaration = root.find(j.ImportDeclaration, {
source: {
type: 'Literal',
value: 'classnames',
},
});
if (!importDeclaration.length) {
return root.toSource();
}
// get the local name for the imported module
const localName = importDeclaration.find(j.Identifier).get(0).node.name;
// find where classnames is being called and replace it with clsx
root.find(j.CallExpression, {
callee: {
type: 'Identifier',
name: localName,
},
}).replaceWith(nodePath => {
const {node} = nodePath;
node.callee.name = 'clsx';
return node;
});
// replace import
importDeclaration.replaceWith(nodePath => {
const {node} = nodePath;
node.specifiers[0].local.name = 'clsx';
node.source.value = 'clsx';
return node;
});
return root.toSource({
quote: 'single',
});
};
import classnames from 'classnames';
function example() {
return classnames({
objectKeyClass: true
}, 'another-class');
}
import clsx from 'clsx';
function example() {
return clsx({
objectKeyClass: true
}, 'another-class');
}
@mocanew
Copy link
Copy Markdown
Author

mocanew commented Mar 16, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment