Using webpack-bundle-analyzer we detected the module StoreDevtoolsModule into the angular production bundle of one of our customers.
This is the usual configuration for ngRx initialization for the StoreDevtoolsModule
module:
(....)
// \/ this one
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
@NgModule({
imports: [
(....),
!environment.production ? StoreDevtoolsModule.instrument() : [],
(....),
],
})
export class AppModule {}
Angular’s three shaking does not remove the StoreDevtoolsModule
module from the bundle, because the evaluation of requiring or not this module happens are runtime.
The cause is the ternary: !environment.production ? StoreDevtoolsModule.instrument() : []
To prevent this module from making into the production bundle, we will need to
- modify this ternary so it is evaluated in a separated file
- configure an angular replace file build action.
first create 2 files:
one to host the import array for non-prod (default), with the following contents
src/hat-trick/store-dev-tools-import.ts
import { environment } from 'src/environments/environment';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
export const storeDevToolsImport = [
!environment.production ? StoreDevtoolsModule.instrument() : []
];
and the other to host the import array for prod builds, with the following contents
src/hat-trick/store-dev-tools-import.prod.ts :
export const storeDevToolsImport = [];
add a fileReplacements
section to your angular.json
file at the production build config:
"production": {
(....)
"fileReplacements": [
(....)
{
"replace": "src/hat-trick/store-dev-tools-import.ts",
"with": "src/hat-trick/store-dev-tools-import.prod.ts"
},
]
}
and finally, use the new variable storeDevToolsImport
in you module, instead of importing StoreDevtoolsModule
directly:
@NgModule({
imports: [
(....),
...storeDevToolsImport,
(....),
],
})
export class AppModule {}
And done! next time you build in prod mode, StoreDevtoolsModule will no longer be included (saving about 4kb)
NgRx docs have since provided a similar solution in a hidden spot