Remove `@ngrx/store-devtools` in production
Published on October 30, 2023
In production @ngrx/store-devtools
should be completly removed from the bundle.
Let’s see an example:
Start a new angular application
npx @angular/cli@latest new ngrx-remove-devtools --style css --routing false --minimal
Install @ngrx/store
and @ngrx/store-devtools
cd ngrx-remove-devtoolsnpx ng add @ngrx/store --skip-confirmationnpx ng add @ngrx/store-devtools@latest --skip-confirmation
Populate your state
@NgModule({ declarations: [AppComponent], imports: [ BrowserModule, StoreModule.forRoot( { counter: () => 0, }, {} ), StoreDevtoolsModule.instrument({maxAge: 25, logOnly: !isDevMode()}), ], providers: [], bootstrap: [AppComponent],})export class AppModule {}
Examine the state
If you have the Redux dev tools installed you can now examine your state.
ng serve
Problem examine state in Production
It’s best to disable redux dev tools in production.
npx ng buildcd dist/ngrx-remove-devtoolsnpx http-server
Redux dev tools still works in production
Solution 1
If on production do not place the StoreDevtoolsModule.instrument
in the imports array.
npx ng generate environments
add a production
key to the environments files:
export const environment = { production: false,};
export const environment = { production: true,};
import {environment} from '../environments/environment';
@NgModule({ declarations: [AppComponent], imports: [ BrowserModule, StoreModule.forRoot( { counter: () => 0, }, {} ), !environment.production ? StoreDevtoolsModule.instrument({maxAge: 25, logOnly: !isDevMode()}) : [], ], providers: [], bootstrap: [AppComponent],})export class AppModule {}
Problem
@ngrx/store-devtools
is still in the bundle
npx ng build --source-mapnpx source-map-explorer dist/ngrx-remove-devtools/main.4a92d461e97ce051.js
it will add around 16kb
of unused code to your bundle.
Replace app.module.ts
We can achieve the same result with fileReplacement
.
import {BrowserModule} from '@angular/platform-browser';import {StoreModule} from '@ngrx/store';
export const commonImports = [ BrowserModule, StoreModule.forRoot( { counter: () => 0, }, {} ),];
import {StoreDevtoolsModule} from '@ngrx/store-devtools';import {commonImports} from './imports.common';import {isDevMode} from '@angular/core';
export const imports = [ ...commonImports, StoreDevtoolsModule.instrument({maxAge: 25, logOnly: !isDevMode()})];
import {commonImports} from './imports.common';
export const imports = [...commonImports];
import {NgModule} from '@angular/core';import {AppComponent} from './app.component';import {imports} from './imports';
@NgModule({ declarations: [AppComponent], imports: [...imports], providers: [], bootstrap: [AppComponent],})export class AppModule {}
@ngrx/store-devtools
is completly removed from the bundle.