Babel Plugin to Remove React PropTypes

0.4.24 · active · verified Sun Apr 19

This Babel plugin, currently at version `0.4.24`, is designed to optimize React applications by effectively removing `propTypes` definitions from the production build. `propTypes` are primarily utilized for development-time type checking and debugging, and thus represent unnecessary overhead in production bundles, contributing to larger file sizes and increased load times. The plugin offers distinct `mode` options: `remove` (the default for most applications), `wrap`, and `unsafe-wrap`. The `wrap` and `unsafe-wrap` modes are specifically tailored for React library authors, enabling them to retain some `propTypes` behavior in development while ensuring optimization for production scenarios. The `remove` mode is generally recommended for direct application authors seeking maximum bundle size reduction. The project exhibits a consistent, albeit at times gradual, release cadence, with recent patches focusing on improved type checking logic, custom `createReactClass` function support, and more robust handling of unused identifier removal. It integrates seamlessly into the Babel ecosystem, typically configured via standard Babel configuration files such as `.babelrc` or `babel.config.js`.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to integrate and use `babel-plugin-transform-react-remove-prop-types` via Babel's Node API. It transforms a React component, removing its `propTypes` and the `prop-types` import statement in a simulated production environment.

const babel = require('@babel/core');
const code = `
  import PropTypes from 'prop-types';
  const MyComponent = ({ value }) => <div>{value}</div>;
  MyComponent.propTypes = {
    value: PropTypes.string.isRequired
  };
`;

// Simulate a production environment for the plugin to activate
process.env.NODE_ENV = 'production';

const result = babel.transformSync(code, {
  filename: 'my-component.js',
  plugins: [
    // Required for Babel to parse JSX and ES modules before this plugin runs
    ['@babel/plugin-transform-react-jsx', { pragma: 'React.createElement' }],
    ['@babel/plugin-transform-modules-commonjs', { loose: true }],
    // The plugin itself, configured for removal
    ['babel-plugin-transform-react-remove-prop-types', {
      mode: 'remove', // Default is 'remove', can also be 'wrap' or 'unsafe-wrap'
      ignoreFilenames: ['node_modules'], // Example option: ignore files in node_modules
      removeImport: true // Also remove the 'import PropTypes from "prop-types"' statement
    }]
  ]
});

console.log('Transformed Code (Production):\n', result.code);

// Reset NODE_ENV to avoid affecting other tests or processes
process.env.NODE_ENV = 'test';

view raw JSON →