Last active
February 9, 2022 12:02
-
-
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
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
| 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', | |
| }); | |
| }; |
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
| import classnames from 'classnames'; | |
| function example() { | |
| return classnames({ | |
| objectKeyClass: true | |
| }, 'another-class'); | |
| } |
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
| import clsx from 'clsx'; | |
| function example() { | |
| return clsx({ | |
| objectKeyClass: true | |
| }, 'another-class'); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
clsx npm module
benchmarks