angular - 在生产模式下禁用指令
问题描述
在我的项目中,我们为 E2E 测试需要针对的大多数元素提供了类:
<div class="just-an-item" [e2e] [e2e-class]="button-to-trigger-something">...</div>
哪个被编译成
<div class="just-an-item e2e-button-to-trigger-something">...</div>
感谢这个指令
@Directive({
selector: '[e2e]'
})
export class E2eClassDirective implements OnInit {
@HostBinding('class')
public classes: string;
@Input('e2e-class')
public readonly className: string;
constructor (
private host: ElementRef,
private renderer: Renderer2
) {
}
public ngOnInit (): void {
this.renderer.addClass(
this.host.nativeElement,'e2e-' + this.className // <-------
);
}
}
当然我有一个模块
@NgModule({
...
declarations: [ ... ... E2eClassDirective ],
...
})
export class MainModule {}
我想在编译时禁用它,而不是在执行时禁用。
换句话说,我不希望这样:
public ngOnInit (): void {
if( !environment.production ) {
this.renderer.addClass(
this.host.nativeElement,'e2e-' + this.className // <-------
);
}
}
因为这仍然意味着文本将在编译版本中,并且将执行逻辑。相反,如果我们在生产模式下构建应用程序,我希望能够“禁用”它,这样它就不会进入/dist
.
那可能吗?
解决方案
一种可能的解决方案是创建此文件的 2 个版本,例如some.component.ts
和一个生产版本some.component.prod.ts
然后使用Angular 的文件替换fileReplacement
并在文件中添加一个项目angular.json
:
{
...
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
},
{
"replace": "path/to/some.component.ts",
"with": "path/to/some.component.prod.ts"
}
]
}
}
...
}
`
推荐阅读
- cassandra - 在 Cassandra 中,如何将数据保存在列名中,同时将列值留空?
- hyperledger-fabric - Hyperledger 无法更新通道
- android - Android Studio XML 格式不填满屏幕
- markdown - 在 github 页面的降价表中
- python - POST 方法在被请求时不断发送 400 错误
- java - 无法启动剪贴簿虚拟机
- laravel - 如何翻译 Laravel 分页?
- node.js - postgresql to_char(date, 'day') 使用nodejs时得到不同的结果
- html - 使用 Bootstrap 创建统一的按钮组
- python - 管理 conda 和 pip 之间依赖关系的最佳实践