Is it possible to import BrowserModule conditionally inside a @NgModule (not AppModule)?

42 views Asked by At

I have this situation in my Angular application: I have the AppModule with several imported Modules, including BrowserModule, of course. In another module of my app (I have an AppRoutingModule that manages the routes, each with its own module) I would like to conditionally imports BrowserModule because this particular module can be

  • a simple module of this app (and I don't need to import BrowserModule inthis case)
  • or a Parcel, which I'll export and I'll import into another project (and in this case I need to import BrowserModule, otherwise it doesn't work as a standalone module)

As you can see in the example below, I tried to import this module conditionally, based on window.location.href (in this way I can check which application is running) but the app compilation fails. There are several errors, it no longer recognizes the NewRequestComponent elements.

import {CommonModule} from '@angular/common';

import {NewRequestRoutingModule} from './new-request-routing.module';
import {NewRequestComponent} from './pages/new-request/new-request.component';
import {SharedModule} from '@app/shared';
import {BrowserModule} from '@angular/platform-browser';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

const isParcelComponent = !window.location.href.includes('/appric');

@NgModule({
  declarations: [
    NewRequestComponent,
  ],
  imports: [
    CommonModule,
    isParcelComponent ? BrowserModule: [],
    NewRequestRoutingModule,
    SharedModule,
  ],
  bootstrap: [NewRequestComponent],
})
export class NewRequestModule {}

This is an example of error

enter image description here

Do you know why compilation fails or how can I achieve my goal? Thank you in advance

1

There are 1 answers

1
Miguel Garcia On

I get why you thought not importing the browserModule in a simple component would be a good idea, but in Angular we need browserModule imported in the root module (AppModule), it provides essential features that Angular needs to launch and run the application. The way modules should be organized is:

AppModule (root module): It should contain only the essential imports that every other module needs to work properly, BrowserModule is one of them. If you have any another module it should also be contained in the root module.

AnyOtherModule: Should contain the dependencies necessary to its components only and can not reimport imports already imported in the AppModule, as it is already imported in the AppModule and have its dependencies already imported

It is not a good practice and i dont even know if it is possible to import condicionally a dependency, if you want something similar use a hierarchy of modules