babel-plugin-transform-react-class-to-function
raw JSON → 1.2.2 verified Sat Apr 25 auth: no javascript maintenance
A Babel 7 plugin that transforms React class components into functional components. Current stable version is 1.2.2. Release cadence is low; last update was several years ago. Key differentiator: automates conversion to reduce bundle size, avoids manual refactoring. Compared to alternatives like babel-plugin-transform-react-pure-class-to-function, it supports Babel 7 and offers a 'memo' option to handle PureComponent and shouldComponentUpdate.
Common errors
error Error: Cannot find module 'babel-plugin-transform-react-class-to-function' ↓
cause Plugin not installed as a dependency.
fix
Run: npm install --save-dev babel-plugin-transform-react-class-to-function
error TypeError: Cannot read property 'replaceWith' of null ↓
cause Plugin encountered a class component that it could not parse, possibly due to unsupported syntax.
fix
Ensure your Babel configuration includes presets for React and modern JavaScript (e.g., @babel/preset-react, @babel/preset-env).
Warnings
gotcha Transforms only components extending React.Component or React.PureComponent; custom base classes are ignored. ↓
fix Ensure classes extend React.Component or PureComponent directly, not custom superclasses.
gotcha Lifecycle methods other than render (e.g., componentDidMount) are removed, which may break functionality. ↓
fix Only use this plugin for components that have no lifecycle methods or state; otherwise, refactor manually.
gotcha The 'memo' option wraps components in React.memo but does not convert if shouldComponentUpdate is implemented without PureComponent. ↓
fix Set options: { memo: true } to handle PureComponent; manually memoize components with custom shouldComponentUpdate.
Install
npm install babel-plugin-transform-react-class-to-function yarn add babel-plugin-transform-react-class-to-function pnpm add babel-plugin-transform-react-class-to-function Imports
- default wrong
const plugin = require('babel-plugin-transform-react-class-to-function')correctimport plugin from 'babel-plugin-transform-react-class-to-function' - plugin wrong
module.exports = { plugins: [require('babel-plugin-transform-react-class-to-function')] }correctmodule.exports = { plugins: ['babel-plugin-transform-react-class-to-function'] } - transformSync wrong
transformSync(code, { plugins: [require('babel-plugin-transform-react-class-to-function')] })correctimport { transformSync } from '@babel/core'; transformSync(code, { plugins: ['babel-plugin-transform-react-class-to-function'] })
Quickstart
// babel.config.js
module.exports = {
plugins: ['babel-plugin-transform-react-class-to-function']
};
// Input: class Hello extends React.Component { render() { return <div>Hi</div> } }
// Output: const Hello = () => <div>Hi</div>