angular - 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
}
解决方案
推荐阅读
- python - 如何找到当前函数的名称?
- php - 这段代码,但部分 href='allowbook.php?giv= '
- javascript - Range slider with min and max values limites
- javascript - 如何通过过滤获取的数据来更新状态?
- c# - 在 TT 自动化脚本中跳过解决方案文件夹
- r - 拟合 DCC GARCH 模型后 Li Mak 检验的误差
- machine-learning - 强化学习 - 如何处理进行数字近似的不同数量的动作
- javascript - 为什么我不能在 addEventListener 中调用类函数
- javascript - 为什么这个画布绘图会导致内存泄漏?
- c# - C# Forms - 如何在现有面板上绘制形状