Skip to content

babel-traverse, var declarations not included in binding references #4694

@kentcdodds

Description

@kentcdodds

Input Code

var a = 32
var {c: b} = obj

console.log(a, b)

ASTExplorer.net example

https://astexplorer.net/#/jUTCWsdHdx/3

Description of Behavior

The VariableDeclarator a should be included in it's own path.scope.getBinding(path.node.name).referencePaths, just like the VariableDeclarator b which is an ObjectProperty in an ObjectPattern.

Possible Solution

I'm not sure what is causing this, but for some reason, this code isn't called for the VariableDeclarator's Identifier.

Context

I'm writing a tool that removes unused variables. For example:

function sortRankedItems(a, b) {
  var {rank: aRank} = a
  var bRank = b.rank

  var same = aRank === bRank
  return 'blah'
}

With my tool, would result in:

function sortRankedItems(a, b) {
  return 'blah'
}

Based on the order the plugins are running, when the visitor comes across aRank and bRank, it looks like those variables are in use, but when the visitor gets to same, it removes the node. Then it searches for the references that were used by same and determines whether it is safe to now remove those as well. Because of this bug, bRank is not able to be removed because it's not in the referencePaths, so I can't find it from the same node. Hopefully that makes sense.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions