index.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. module.exports = babel => {
  2. const t = babel.types
  3. return {
  4. inherits: require('babel-plugin-syntax-jsx'),
  5. visitor: {
  6. Program (path) {
  7. path.traverse({
  8. 'VariableDeclaration' (path) {
  9. if (path.node.declarations.length !== 1 ||
  10. !t.isVariableDeclarator(path.node.declarations[0]) ||
  11. !t.isArrowFunctionExpression(path.node.declarations[0].init)) {
  12. return
  13. }
  14. const jsxChecker = {
  15. hasJsx: false
  16. }
  17. path.traverse({
  18. JSXElement () {
  19. this.hasJsx = true
  20. }
  21. }, jsxChecker)
  22. if (!jsxChecker.hasJsx) {
  23. return
  24. }
  25. const name = path.node.declarations[0].id.name
  26. const params = [t.identifier('h'), ...path.node.declarations[0].init.params]
  27. const body = path.node.declarations[0].init.body
  28. const isDevEnv = process.env.NODE_ENV === 'development'
  29. const props = [
  30. t.objectProperty(
  31. t.identifier('functional'),
  32. t.booleanLiteral(true)
  33. ),
  34. t.objectProperty(
  35. t.identifier('render'),
  36. t.arrowFunctionExpression(params, body)
  37. )
  38. ]
  39. if (isDevEnv) {
  40. props.unshift(
  41. t.objectProperty(
  42. t.identifier('name'),
  43. t.stringLiteral(name)
  44. )
  45. )
  46. }
  47. path.replaceWith(
  48. t.variableDeclaration(
  49. 'const',
  50. [
  51. t.variableDeclarator(
  52. t.identifier(name),
  53. t.objectExpression(
  54. props
  55. )
  56. )
  57. ]
  58. ),
  59. []
  60. )
  61. }
  62. })
  63. }
  64. }
  65. }
  66. }