首页 > 解决方案 > Angular/Typescript 在编译时删除未使用的代码

问题描述

我正在使用 Angular 9,我有一些这样的代码:

(features.ts, autogenerated:)
// AUTO-GENERTATED FILE. DO NOT EDIT!
export const Features = {
  // Whether to reveal our Secret New Feature to the world
  ENABLE_SECRET_FEATURE: 1
};

(mycode.ts, app code)
import { Features } from 'generated/features.ts';

function doSomething() {
  if (Features.ENABLE_SECRET_FEATURE) {
    doAIBlockChainARThing();
  } else {
    doSomeBoringOldCRUDThing();
  }
}

我希望发出的代码是

function doSomething() {
    doAIBlockChainARThing();
}

或者

function doSomething() {
    doSomeBoringOldCRUDThing();
}

但不是两者兼而有之。

是否有调用ng build会发生这种情况?我知道 uglify 可以做到这一点,而 Closure Compiler 肯定可以。我当前的调用是:ng build --aot=true --stats-json --buildOptimizer=true --optimization=true --prod

更新:

经过一些实验后,我发现 Angular prod builds 中的简洁设置可以满足我的要求,如果我有如下代码:

const SECRET_FEATURE = true;
if (SECRET_FEATURE) {
  // code here is emitted
} else {
  // code here is NOT emitted
}

但是,如果我尝试做类似的事情:

import {SECRET_FEATURE} from 'my-features';

if (SECRET_FEATURE) { // this conditional is emitted
  // this code is emitted
} else {
  // this code is also emitted
}

标签: angulartypescript

解决方案


推荐阅读