Last active
May 27, 2019 10:31
-
-
Save LucaColonnello/4114c8beb45d77ecf3a08213f92589da to your computer and use it in GitHub Desktop.
Babel named default export React plugin
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
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 }); | |
} | |
} | |
}; | |
} |
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 (props) => ( | |
<span>Test</span> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://astexplorer.net/#/gist/dbd75b848c8c7ca7722211f484db387a/335e3ada7b525e1efa5e0e3cc14ddb405bfb0fe6