• Stars
    star
    898
  • Rank 50,853 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 9 years ago
  • Updated almost 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Remove unnecessary React propTypes from the production build. 🎈

babel-plugin-transform-react-remove-prop-types

Remove unnecessary React propTypes from the production build.

npm version npm downloads Build Status

Dependencies DevDependencies

Installation

npm install --save-dev babel-plugin-transform-react-remove-prop-types

The problem solved

Remove React propTypes from the production build, as they are only used in development. You can save bandwidth by removing them.

Example

In

const Baz = (props) => (
  <div {...props} />
);

Baz.propTypes = {
  className: PropTypes.string
};

Out

const Baz = (props) => (
  <div {...props} />
);

With comment annotation

The majority of cases should be addressed by default by this plugin.

In some cases, for example when using HOCs (High Order Components), like react-redux's connect, or component inheritance (although it's NOT recommended), a comment after the propTypes definition may be used to force the removal:

Component.propTypes /* remove-proptypes */ = {}

Usage

Via .babelrc (Recommended)

.babelrc

without options:

{
  "env": {
    "production": {
      "plugins": ["transform-react-remove-prop-types"]
    }
  }
}

with options:

{
  "env": {
    "production": {
      "plugins": [
        ["transform-react-remove-prop-types", {
          "mode": "wrap",
          "ignoreFilenames": ["node_modules"]
        }]
      ]
    }
  }
}

Via CLI

babel --plugins transform-react-remove-prop-types script.js

Via Node API

without options:

require('babel-core').transform('code', {
  plugins: [
    'transform-react-remove-prop-types',
  ],
});

with options:

require('babel-core').transform('code', {
  plugins: [
    [
      'transform-react-remove-prop-types',
      {
        mode: 'wrap',
        ignoreFilenames: ['node_modules'],
      },
    ],
  ],
});

Options

mode

  • remove (default): the propTypes definitions are removed from the source code.
  • wrap: the propTypes definitions are wrapped with the following code:
Component.propTypes = process.env.NODE_ENV !== "production" ? {
  // ...
} : {};

Accessing Component.propTypes.className won't throw. It's a tradeoff between the size of the output file and the likelihood libraries like react-native-hyperlink breaks.

  • unsafe-wrap: the propTypes definitions are wrapped with the following code:
if (process.env.NODE_ENV !== "production") {
  Component.propTypes = {
    // ...
  }
}

Accessing Component.propTypes.className will throw.

The wrap modes are targeting React libraries like material-ui or react-native-web. They are not intended to be used by application authors.

removeImport

  • true: the import statements are removed as well. This option only works if mode is set to remove:
import PropTypes from 'prop-types'
  • false (default): does not remove the import statements.

ignoreFilenames

This filter generates a regular expression. Any filenames containing one of the array's strings will be ignored. By default, we match everything.

Following the Is it safe? section, you might encounter a component depending on the propTypes at runtime to work. For this reason, we provide an array options to filter out some files and folders. For instance, you can ignore all the npm modules:

ignoreFilenames: ['node_modules'],

additionalLibraries

This option gives the possibility to remove other propTypes in addition to the canonical prop-types.

For instance, by default

import PropTypes from 'prop-types'
import ImmutablePropTypes from 'react-immutable-proptypes'

will result in the latter not to be removed, while with:

additionalLibraries: ['react-immutable-proptypes'],

both will be removed.

Regular expressions

If you are using Babel 7 or newer and your config is stored in babel.config.js, you can also use a regular expression to describe modules, which should be removed.

This would be particularly useful when using custom prop types validators, implemented as part of your own source code. For example

import CustomPropTypes from '../../prop-types/my-own-validator'
import OtherCustomPropTypes from '../../prop-types/my-other-validator'

would be removed with the following setting

additionalLibraries: [/\/prop-types\/.*$/]

If you use an index file

import CustomPropTypes from '../../prop-types'

you could set it up as

additionalLibraries: [/\/prop-types$/]

classNameMatchers

Use this option to enable this plugin to run on components that extend a class different than React.Component or React.PureComponent.

Given this example:

class MyComponent extends BaseComponent {
  ...
}

You would use:

classNameMatchers: ["BaseComponent"]

createReactClassName

Use this option to set a custom name for the import of the create-react-class package that is different than createReactClass.

Given this example:

import createClass from 'create-react-class';

You would use:

createReactClassName: 'createClass'

Is it safe?

If you are using the propTypes in a conventional way, i.e by using them to perform type checking on the properties, that plugin should be safe to use.

However, some libraries are accessing the propTypes on the component directly. For instance react-native-vector-icons use them to split the properties between two components:

const touchableProps = pick(restProps, Object.keys(TouchableHighlight.propTypes));

⚠️ The plugin is breaking that code if it ends up removing TouchableHighlight.propTypes.

Make sure you are:

  • Not using that pattern in your source code. If you do, explicitly export the propTypes to work around that limitation.
  • Not parsing the node_modules. If you do, test that your code is still working before shipping into production.

eslint-plugin-react has a rule forbid-foreign-prop-types that can help you make this plugin safer to use.

License

MIT

More Repositories

1

react-swipeable-views

A React component for swipeable views. ❄️
JavaScript
4,450
star
2

serviceworker-webpack-plugin

Simplifies creation of a service worker to serve your webpack bundles. ♻️
JavaScript
458
star
3

babel-plugin-react-remove-properties

Babel plugin for removing React properties. 💨
JavaScript
380
star
4

react-event-listener

A React component for binding events on the global scope. 💫
JavaScript
359
star
5

a-journey-toward-better-style

A Journey toward better style
JavaScript
263
star
6

i18n-extract

Manage localization with static analysis. 🔍
JavaScript
170
star
7

SplitMe

Split expenses with friends.
JavaScript
154
star
8

browser-metrics

A collection of metrics tools for measuring performance ⚡️
JavaScript
125
star
9

babel-plugin-transform-dev-warning

Remove development warning from production code
JavaScript
15
star
10

react-benchmark

Environment to benchmark React Component 🏁
JavaScript
14
star
11

react-with-styles-interface-jss

Interface to use react-with-styles with JSS. 🐠
JavaScript
12
star
12

plume

Plume is an accurate indoor tracking system which uses the power of magnetic fields to compute a device's position and orientation. We are aiming at an accuracy of less than a centimeter for the position, and less than a degree for the orientation.
C
9
star
13

material-ui-generate-css-file

CSS
5
star
14

Kinect

Kinect processing
Java
4
star
15

Salonrama

PHP
3
star
16

mui-olivier-tools

TypeScript
3
star
17

mui-merge

test-repo
JavaScript
2
star
18

ELEC222

Architectures reconfigurables et langages HDL
VHDL
2
star
19

ELEC223

Pratique des systèmes à microprocesseurs
C
2
star
20

react-conf-2024-pigment-css

TypeScript
2
star
21

toolpad-issue-2340

https://github.com/mui/mui-toolpad/issues/2340
2
star
22

bug-markdown-release

2
star
23

AirDJ

AirDJ est un logiciel qui permet de mixer de la musique à partir du mouvement des mains, grâce à une kinect.
Java
2
star
24

test-appsmith

1
star
25

appsmith-git-sync

1
star
26

SplitMeBord

Présentation pour le cours de SIM203 - Entrepreneuriat
JavaScript
1
star
27

fooc-nextjs-css-modules

TypeScript
1
star
28

tmp

1
star
29

next-55817

CSS
1
star