I have a core, shared and many features modules in an Angular 5 app. Each of these features modules are lazy loaded.
Almost all of them have dependencies on each other. As an example, I have a lazy loaded message module that depends on another lazily loaded module (not core, not shared) for resolving route data.
When I compile the app with yarn start
, everything works fine. Though, when I try to build the app with ng build --prod
and the AOT kicks in, I'm getting the following error :
ERROR in: Encountered undefined provider! Usually, this means you have a circular dependency (might be caused by using 'barrel' index.ts files.
What bugs me is the fact that no circular dependencies are flagged on build time.
If I build the app without AOT, with ng build --no-aot --prod
, I'm getting no error and everything works fine.
I tried to eject the app from the angular CLI to directly build the app with the webpack task, but with no result or detail on what's happening.
Where do I start to debug this problem?
I'm using a lot of barrel files in my app. Each of them has a similar structure like this (style borrowed from Todd Motto's NGRX course) :
import { AlertsComponent } from '@alerts/containers/alerts/alerts.component';
import { AlertComponent } from '@alerts/containers/alert/alert.component';
export const containers: Array<any> = [AlertsComponent, AlertComponent];
export * from '@alerts/containers/alerts/alerts.component';
export * from '@alerts/containers/alert/alert.component';
And these containers are spread in the module like this :
import * as fromAlertsContainers from '@alerts/containers';
import * as fromCoreGuards from '@core/guards';
@NgModule({
imports: [RouterModule.forChild(routes), SharedModule, CommonModule],
providers: [...fromCoreGuards.guards],
declarations: [...fromAlertsContainers.containers],
exports: [...fromAlertsContainers.containers]
})
export class AlertsModule {}
I'm a doing something wrong ? Why does it work with yarn start
and not with ng build --prod
?
Testing #1 : using forwardRef as a patch.
Currently testing the following solution, I'll keep you in touch if it works/fix the problem :
@Inject(forwardRef(() => ApiService))
private apiService: ApiService
Solution!
Here is how I fixed the problem.
- Removed all the
providers
from the AppModule. - Reinserting each of them one by one.
- After each insert, I ran
ng build --prod
then waited for the build result. It turns out, I had the following code that caused the circular
dependency : providers: [ Location, { provide: LocationStrategy, useClass: PathLocationStrategy }, { provide: HTTP_INTERCEPTORS, useClass: AuthTokenInterceptor, multi: true } ]
PathLocationStrategy
needed Location
and Location
needed PathLocationStrategy
.
npm run ionic:build --prod