【问题标题】:Conditional using isDevMode is not being tree shaked条件使用 isDevMode 不会被摇树
【发布时间】:2020-12-18 14:00:02
【问题描述】:

我当前的代码是:

@Directive({
  selector: 'some-selector',
})
export class SomeSelectorDirective {
  constructor() {
    if (isDevMode() && someCondition) {
      console.warn('Some warning.');
    }

    // some omitted code
  }
}

问题是,当我运行ng build --prod 时,这种情况并没有被摇动,但是如果我用!environment.production 替换isDevMode(),代码就会被删除。我想知道其中的原因:为什么 isDevMode 包装的代码不被丢弃在构建产品上?


请注意,我使用的是 Angular 10.x.y。

【问题讨论】:

    标签: angular webpack angular-cli tree-shaking


    【解决方案1】:

    这是因为优化器 (Terser.js) 没有应用该函数来检查它的运行时值。

    当你使用内联版本时,webpack 的DefinePlugin 会将内联替换为它自己的值,因此在优化之前它看起来像:

    @Directive({
      selector: 'some-selector',
    })
    export class SomeSelectorDirective {
      constructor() {
        if (false && someCondition) {
        // ---^ inlined the false value
          console.warn('Some warning.');
        }
    
        // some omitted code
      }
    }
    

    使用此代码,优化器可以肯定地删除 if,因为它是一个“死”分支。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      • 2019-04-24
      • 2016-11-17
      • 2019-12-29
      • 1970-01-01
      • 2021-07-17
      • 2020-10-18
      相关资源
      最近更新 更多