Search code examples
javascriptminifybabeljs

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


Solution

  • 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.