Skip to content

Instantly share code, notes, and snippets.

@bodhi
Created July 20, 2016 03:29
Show Gist options
  • Save bodhi/469282221279315b75ab64087131ca43 to your computer and use it in GitHub Desktop.
Save bodhi/469282221279315b75ab64087131ca43 to your computer and use it in GitHub Desktop.
Map `<A intlId={blah} intlValues={blahVal} />` to `<A><Message id={blah} values={blahVal} /></A>`
function mapIntl(j, path) {
const intlIdAttr = path.value.openingElement.attributes.find(
({
name: { name }
}) => name === 'intlId'
);
const intlValAttr = path.value.openingElement.attributes.find(
({
name: { name }
}) => name === 'intlValues'
);
const attributes = [j.jsxAttribute(j.jsxIdentifier('id'), intlIdAttr.value)]
if (intlValAttr) {
attributes.push(j.jsxAttribute(j.jsxIdentifier('values'), intlValAttr.value));
}
const message = j.jsxElement(
j.jsxOpeningElement(
j.jsxIdentifier('Message'),
attributes,
true
),
null
);
const replacement = j.jsxElement(
j.jsxOpeningElement(
path.value.openingElement.name,
path.value.openingElement.attributes.filter(a => (a !== intlIdAttr && a !== intlValAttr))
),
j.jsxClosingElement(
path.value.openingElement.name
),
[j.literal("\n"), message, j.literal("\n")],
path.value.openingElement.name,
false
);
return replacement;
}
module.exports = function(fileInfo, api) {
const j = api.jscodeshift
const v = j(fileInfo.source)
.findJSXElements()
.filter(j.filters.JSXElement.hasAttributes({ intlId: () => true }))
.replaceWith(p => mapIntl(j, p));
return v.toSource();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment