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

Transform error with mode=wrap for TypeScript class component static propTypes type definition #197

Open kryops opened 3 years ago

kryops commented 3 years ago

Code (TypeScript):

import React, { Component } from 'react';

export class Foobar extends Component {

    static propTypes: {};

    render() {
        return null;
    }
}

Foobar.propTypes = {};

Config:

{
  "presets": [
    "@babel/preset-react",
    "@babel/preset-typescript"
  ],
  "plugins": [
    ["transform-react-remove-prop-types", {
      "mode": "wrap"
    }]
  ]
}

throws the error

$ babel index.tsx
TypeError: /home/michael/git/babel-prop-types-issue/index.tsx: Property right of AssignmentExpression expected node to be of a type ["Expression"] but instead got undefined
    at Object.validate (/home/michael/git/babel-prop-types-issue/node_modules/@babel/types/lib/definitions/utils.js:132:11)
    at validateField (/home/michael/git/babel-prop-types-issue/node_modules/@babel/types/lib/validators/validate.js:24:9)
    at validate (/home/michael/git/babel-prop-types-issue/node_modules/@babel/types/lib/validators/validate.js:17:3)
    at builder (/home/michael/git/babel-prop-types-issue/node_modules/@babel/types/lib/builders/builder.js:38:27)
    at Object.assignmentExpression (/home/michael/git/babel-prop-types-issue/node_modules/@babel/types/lib/builders/generated/index.js:260:31)
    at remove (/home/michael/git/babel-prop-types-issue/node_modules/babel-plugin-transform-react-remove-prop-types/lib/remove.js:77:54)
    at ClassProperty (/home/michael/git/babel-prop-types-issue/node_modules/babel-plugin-transform-react-remove-prop-types/lib/index.js:253:37)
    at NodePath._call (/home/michael/git/babel-prop-types-issue/node_modules/@babel/traverse/lib/path/context.js:55:20)
    at NodePath.call (/home/michael/git/babel-prop-types-issue/node_modules/@babel/traverse/lib/path/context.js:42:17)
    at NodePath.visit (/home/michael/git/babel-prop-types-issue/node_modules/@babel/traverse/lib/path/context.js:92:31) {
  code: 'BABEL_TRANSFORM_ERROR'
}
ifree92 commented 3 years ago

For me, that doesn't work completely with *.tsx files. After compilation - propTypes object is absent.

ifree92 commented 3 years ago

The better solution I found:

MyComponent['propTypes'] = { ... };
rpearce commented 2 years ago

@kryops I just randomly found this, but shouldn't it be static propTypes = {};, not with a :?

kryops commented 2 years ago

@rpearce that would be the workaround.

The above code is however valid TypeScript, first only declaring the member and its type, then assigning its value later. When migrating our codebase to TypeScript, this was the minimal change required to make TypeScript happy about the prop types.