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

Remove unnecessary React propTypes from the production build. :balloon:
MIT License
897 stars 61 forks source link

Remove unused MemberExpression root identifiers #158

Closed lencioni closed 6 years ago

lencioni commented 6 years ago

In our codebase, I noticed that we had the following pattern that was not getting properly cleaned up:

const shapePropType = PropTypes.shape({
  foo: PropTypes.string,
});

const ComponentA = () => <div />;

ComponentA.propTypes = {
  foo: shapePropType.isRequired,
};

The notable thing here is that inside the propTypes assignment, a MemberExpression is used instead of just an identifier. However, in our visitor for collecting nested identifiers, we special-cased Identifiers that have a MemberExpression parent to not be collected. This was to prevent the bar portion of foo.bar from being collected. However, in this case, we actually want the foo part of foo.bar to be collected for possible additional cleanup, so we need to add a little more logic to make this happen.

To solve this, I added a function that takes a path and traverses up the tree until it finds the first non-MemberExpression, and then traverses down the left side of that tree until it finds the root identifier. This should be the foo in foo.bar.baz, for instance.

It seems likely that there is a better more built-in Babel way to do this, but I was unable to find anything to point me in that direction so I rolled my own.