angular 中有#define 吗?
Is there a #define in angular?
有什么方法可以用 Angular 实现 #define 功能吗?
我说的是在编译时 add/remove 一些基于定义的代码的能力,就像 C++、C# 和其他较低级别的编程语言一样。
不可能以与 c# 中的预处理器指令完全相同的方式。但是,我假设您希望在生成 js 包时执行此操作。您可以做的是根据环境设置指定要包含的不同文件,但没有办法只省略同一文件中的部分代码。
查看 angular.json
文件和名为 fileReplacements
的部分。在使用 ng new
生成的默认 angular.json
文件中,您可以看到在生产环境 (ng build --prod
) 中包含文件 src/environments/environment.prod.ts
而不是 src/environments/environment.ts
。您可以根据需要扩展它以进行其他替换。
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
}
}
在 angular 中,这是最接近于 C# AFAIK 中预处理器指令的等价物。
不需要插件,可以使用angular原生优化。
import { environment } from '../environments/environment';
if (environment.production) {
console.log('@@@ environment.production @@@');
} else {
console.log('@@@ NOT environment.production @@@');
}
当您 运行 'ng build --prod' 只有第一个条件内的语句将包含在包中,没有 if 语句。
Here the bundle screenshot, I highlighted the generated component code
有什么方法可以用 Angular 实现 #define 功能吗?
我说的是在编译时 add/remove 一些基于定义的代码的能力,就像 C++、C# 和其他较低级别的编程语言一样。
不可能以与 c# 中的预处理器指令完全相同的方式。但是,我假设您希望在生成 js 包时执行此操作。您可以做的是根据环境设置指定要包含的不同文件,但没有办法只省略同一文件中的部分代码。
查看 angular.json
文件和名为 fileReplacements
的部分。在使用 ng new
生成的默认 angular.json
文件中,您可以看到在生产环境 (ng build --prod
) 中包含文件 src/environments/environment.prod.ts
而不是 src/environments/environment.ts
。您可以根据需要扩展它以进行其他替换。
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
}
}
在 angular 中,这是最接近于 C# AFAIK 中预处理器指令的等价物。
不需要插件,可以使用angular原生优化。
import { environment } from '../environments/environment';
if (environment.production) {
console.log('@@@ environment.production @@@');
} else {
console.log('@@@ NOT environment.production @@@');
}
当您 运行 'ng build --prod' 只有第一个条件内的语句将包含在包中,没有 if 语句。
Here the bundle screenshot, I highlighted the generated component code