Created
April 4, 2018 04:09
-
-
Save dantman/6737bc6fda53d8dfff28047995675028 to your computer and use it in GitHub Desktop.
jscodeshift codemod to change <React.Fragment> and <Fragment> to <>
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
module.exports = function (file, api, options) { | |
const j = api.jscodeshift; // alias the jscodeshift API | |
const root = j(file.source); // parse JS code into an AST | |
let mutation = false; | |
const isJSXIdentifier = (node, name) => j.JSXIdentifier.check(node) && node.name === name; | |
// Remove the opening and closing element names if they are Fragment or React.Fragment | |
const update = node => { | |
const {openingElement, closingElement} = node.value; | |
const {name} = openingElement; | |
const isFragment = isJSXIdentifier(name, 'Fragment'); | |
const isReactFragment = j.JSXMemberExpression.check(name) && isJSXIdentifier(name.object, 'React') && isJSXIdentifier(name.property, 'Fragment'); | |
if ((isFragment || isReactFragment) && closingElement && !node.value.openingElement.attributes.length) { | |
openingElement.name = null; | |
closingElement.name = null; | |
mutation = true; | |
} | |
}; | |
// find and update all React.Fragment elements | |
root.findJSXElements() | |
.forEach(update); | |
if (mutation) { | |
return root.toSource(options.printOptions); | |
} | |
return null; | |
}; | |
module.exports.parser = 'babylon'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment