【问题标题】:Disable a Directive in production mode在生产模式下禁用指令
【发布时间】:2020-10-14 13:08:13
【问题描述】:

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

这可能吗?

【问题讨论】:

  • 您是否尝试过有条件地将此指令添加到您的模块中?

标签: angular angular-directive angular9


【解决方案1】:

不支持https://github.com/angular/angular-cli/issues/10999, 但是您可以使用在生产编译之前删除 [e2e] [e2e-class]="button-to-trigger-something" 的脚本来完成 例如创建一个简单的 js,它使用 https://www.npmjs.com/package/replace-in-file 从 html 文件中删除指令, node ./build/pre-build.js &amp;&amp; ng build

【讨论】:

  • 谢谢,这就是我要找的东西,但我的错误是认为它可以在角度编译器 within 中完成。快速提问,这不会真正修改我的文件吗?我想保持我的源代码完整。
  • 我不确定,请参阅docs.npmjs.com/misc/scripts(如果您使用任何类型的构建管道进行生产,那么源代码修改不是问题)
【解决方案2】:

一种可能的解决方案是创建此文件的 2 个版本,例如 some.component.ts 和生产版本 some.component.prod.ts

然后使用angular's file replacement 并在angular.json 文件中的fileReplacement 下添加一个项目:

{
  ...
  "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"
        }
      ]
    }
  }
  ...
}
`

【讨论】:

  • 这很有意义 - 除了environment.ts,我没有想过将这个替换工具用于其他文件
  • [e2e] 属性保留在构建的包中,但它们只是被忽略(而不是渲染)。
猜你喜欢
  • 2019-03-07
  • 2018-10-05
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 2020-01-24
  • 2020-03-19
  • 1970-01-01
相关资源
最近更新 更多