Skip to content

Instantly share code, notes, and snippets.

@dantman
Created April 4, 2018 04:09
Show Gist options
  • Save dantman/6737bc6fda53d8dfff28047995675028 to your computer and use it in GitHub Desktop.
Save dantman/6737bc6fda53d8dfff28047995675028 to your computer and use it in GitHub Desktop.
jscodeshift codemod to change <React.Fragment> and <Fragment> to <>
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);
// print
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