Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove unused binding with self-reference using Babel

Given this input:

const NOT_REFERENCED = 'abc';

class NotReferencedEither extends React.Component {
  static something() {
    // ...
  }
  someMethod() {
    NotReferencedEither.something();
  }
  render() {
    return <span>Foo</span>;
  }
}

And this Babel plugin:

export default function ({types: t}) {
  return {
    visitor: {
      Program(path, state) {
        Object.keys(path.scope.bindings).forEach(bindingName => {
          const binding = path.scope.bindings[bindingName];
          if (!binding.referenced) {
            binding.path.remove();
          }
        });
      },
    }
  };
}

I would expect to end up with an empty file. Unfortunately, since NotReferencedEither has references to itself, it doesn't pass the removal test.

How can I augment this plugin so that NotReferencedEither, having only references to itself, gets removed too?

Live example: http://astexplorer.net/#/SvYcw6Xggc/4

like image 201
steveluscher Avatar asked May 14 '26 15:05

steveluscher


1 Answers

I'm not entirely sure why this works since it is undocumented, but if you call binding.path.scope.crawl() before removing the path it works as expected as seen here.

like image 162
souporserious Avatar answered May 16 '26 04:05

souporserious



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!