Skip to content

Commit

Permalink
build: add tree-shakeable isDevMode with example (#412)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidlj95 authored Apr 24, 2024
1 parent 9b4b8df commit 6d8ba0a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
21 changes: 21 additions & 0 deletions src/app/common/is-dev-mode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* Used to know if we're in dev mode, in the same fashion Angular does
*
* Public API `isDevMode` (https://angular.io/api/core/isDevMode) is more
* stable.
*
* However, given it's a function call, code under `if(isDevMode())` can not be tree-shaken
* So to allow tree-shaking, using a `const` in the same fashion Angular does for their packages.
*
* Simplifying the type to be just an object, to avoid coupling to it. We're not interested in those contents anyway
*
* For instance:
* https://github.com/angular/angular/blob/17.0.7/packages/router/src/router_module.ts#L38-L39
*
* See also:
* - https://github.com/angular/angular/issues/51175
* - https://github.com/angular/angular-cli/issues/23738
* - https://netbasal.com/explore-angular-clis-define-option-effortless-global-identifier-replacement-f08fec7d9243
*/
declare const ngDevMode: boolean
export const isDevMode = typeof ngDevMode === 'undefined' || ngDevMode
11 changes: 8 additions & 3 deletions src/app/common/test-id.directive.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
import { Directive, ElementRef, Input, OnChanges } from '@angular/core'
import { isDevMode } from '@/common/is-dev-mode'

@Directive({
selector: '[appTestId]',
standalone: true,
})
export class TestIdDirective implements OnChanges {
@Input('appTestId') public id!: string
@Input() public appTestId!: string

constructor(private el: ElementRef) {}

ngOnChanges(): void {
this.el.nativeElement.setAttribute(TEST_ID_ATTRIBUTE, this.id)
if (isDevMode) {
this.el.nativeElement.setAttribute(TEST_ID_ATTRIBUTE, this.appTestId)
}
}
}

export const TEST_ID_ATTRIBUTE = 'data-test-id'
// As per Testing Library
// https://testing-library.com/docs/queries/bytestid/
export const TEST_ID_ATTRIBUTE = 'data-testid'

0 comments on commit 6d8ba0a

Please sign in to comment.