loading...

React Class to Functional Component Babel Plugin

shadowtime2000 profile image shadowtime2000 Updated on ・1 min read

I was interested in how tools that analyze and change your code like Babel, ESLint, and Prettier work. I thought to myself, why not make a Babel plugin? So I did.

Overview

This Babel plugin searches for VariableDeclarations and converts them into functional components. Because of limitations and such components cannot use ES6 classes or JSX.

Demo

This:

import React from "react";

const Hey = React.createClass({
  componentDidMount() {
    console.log("a");
    console.log("b");
  },

  render() {
    return React.createElement("div", null, "Hey!");
  },
});

export default Hey;

becomes this:

import React from "react";

function Hey(props) {
  function componentDidMount() {
    console.log("a");
    console.log("b");
  }

  useEffect(componentDidMount);
  return React.createElement(
    "div",
    null,
    "Hey!"
  );
}

export default Hey;

Contributing

Pull requests are welcome if they add new features or integrate more hooks.

Github
NPM

Discussion

pic
Editor guide