react-codemod icon indicating copy to clipboard operation
react-codemod copied to clipboard

[pure-component] Parsing error: Identifier `props` has already been declared

Open davidnormo opened this issue 4 years ago • 3 comments

I'm raising this issue for awareness rather than an ask to fix as I spent some time trying to but found issues in recast which need resolving first.

The Problem

When using the pure-component transform there is an error if a props variable has already been declared in the render method:

// ...inside MyComponent class
render() {
  const { className, ...props } = this.props

The above is transformed into:

function MyComponent(props) {
  const { className, ...props } = props // Parsing error

Investigation

  • I dug in a bit and managed to resolve this trivial case + other variable declaration types (property, rest, member expressions) by renaming them to props2
  • However when I looked at declarations in a nested block scope those would also be renamed when ideally they should remain unchanged
    function MyComponent(props) {
      if (true) {
        const props = 'bar' // scoped to the if statement therefore should not be transformed
      }
    
  • This lead me to look into recast looking up variable bindings by scope and found that recast doesn't support block scoping (https://github.com/benjamn/ast-types/issues/154)
  • If this is sorted out then we can fix this issue more comprehensively in pure-component

Let me know if you want me to share my code so far

davidnormo avatar Dec 01 '20 09:12 davidnormo

Update: I've opened a PR here https://github.com/benjamn/ast-types/pull/455

davidnormo avatar Dec 07 '20 16:12 davidnormo

Running into this issue today using the pure-component transform to update React from 15.6 => 16.8. Is the solution here to wait until the above PR is merged? Any guidance would be highly appreciated!

brayfe avatar Jan 21 '21 17:01 brayfe

@brayfe the PR is a bit stuck at the moment dealing with hoisting within scopes...

But my changes that fixed my trivial case are here: https://github.com/davidnormo/react-codemod/tree/pure-component-fix Just beware that it may break some cases if the props variable is inside a block.

davidnormo avatar Jan 22 '21 11:01 davidnormo