【问题标题】:How to remove unused binding with self-reference using Babel如何使用 Babel 通过自引用删除未使用的绑定
【发布时间】:2015-12-18 22:41:25
【问题描述】:

鉴于此输入:

const NOT_REFERENCED = 'abc';

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

还有这个 Babel 插件:

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();
          }
        });
      },
    }
  };
}

我希望最终得到一个空文件。不幸的是,由于NotReferencedEither 引用了它自己,它没有通过删除测试。

我怎样才能扩充这个插件,以便NotReferencedEither,只有对自身的引用,也被删除?

现场示例:http://astexplorer.net/#/SvYcw6Xggc/4

【问题讨论】:

  • 值得注意的是:如果您注释掉 NotReferencedEither.something(); 行,您最终会得到一个空文件。事实上,问题在于自我参照。
  • 不是您的问题的答案,但删除死代码是一个难题,尤其是在 JS 中。如果React.Component 是一个有副作用的吸气剂怎么办?那么真正的简化版本将是 React.Component; 本身。

标签: javascript minify babeljs


【解决方案1】:

我不完全确定为什么这是有效的,因为它没有记录,但是如果您在删除路径之前调用 binding.path.scope.crawl(),它会按预期工作,如 here 所示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 2023-03-11
    • 2014-05-25
    • 2019-05-01
    • 2016-06-26
    相关资源
    最近更新 更多