Skip to content

Instantly share code, notes, and snippets.

@LucaColonnello
Last active May 27, 2019 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LucaColonnello/4114c8beb45d77ecf3a08213f92589da to your computer and use it in GitHub Desktop.
Save LucaColonnello/4114c8beb45d77ecf3a08213f92589da to your computer and use it in GitHub Desktop.
Babel named default export React plugin
const itReturnsJSX = () => true;
const createNamedComponentVisitor = {
ArrowFunctionExpression(path) {
const { functionName, types: t } = this;
if (itReturnsJSX(path)) {
path.parentPath.replaceWithMultiple([
t.variableDeclaration('const', [
t.variableDeclarator(
t.identifier(functionName),
t.toExpression(path.node)
)
]),
t.expressionStatement(
t.assignmentExpression(
'=',
t.memberExpression(
t.identifier(functionName),
t.identifier('displayName')
),
t.stringLiteral(functionName)
)
),
t.exportDefaultDeclaration(t.identifier(functionName))
]);
}
}
};
export default function (babel) {
const { types: t } = babel;
return {
name: "ast-transform", // not required
visitor: {
ExportDefaultDeclaration(path) {
path.traverse(createNamedComponentVisitor, { functionName: 'testComponent', types: t });
}
}
};
}
export default (props) => (
<span>Test</span>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment