首页 > 解决方案 > 在生产模式下禁用指令

问题描述

在我的项目中,我们为 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.

那可能吗?

标签: angularangular-directiveangular9

解决方案


一种可能的解决方案是创建此文件的 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"
        }
      ]
    }
  }
  ...
}
`

推荐阅读