'Angular lazy loading modules with feature flags

Is it possible to dynamically change which module is lazy loaded based on a flag? For example, I want to load module A if the flag is enabled, otherwise load module B. The key requirement is that it should use the same path, regardless of which module is loaded.

Attempt #1 - dynamic loadChildren()

// Use a service to get the flag. This service would be injected somewhere?
let someFlag = this.someService.getFlagValue();

const routes: Routes = [
{
    path: 'routeA',
    loadChildren: () => {
      if (someFlag === true) {
        return import('./A.module').then(m => m.ModuleA);
      } else {
        return import('./B.module').then(m => m.ModuleB);
      }
    }
}
];

However, this just throws an error when loading the route: Error: Uncaught (in promise): Error: Runtime compiler is not loaded

Attempt #2 - canActivate guard to replace loadChildren

const routes: Routes = [
{
    path: 'routeA',
    canActivate: [CanActivateFeatureFlagGuard],
    loadChildren: () => import('./A.module').then(m => m.ModuleA),
    data: {
      REPLACE_WITH: () => import('./B.module').then(m => m.ModuleB),
      preload: false
    }
}
]

This throws an compile error:

Function expressions are not supported in decorators in 'routes'
'routes' contains the error at routing.module.ts

referring to the line with REPLACE_WITH.

Is there any known way (perhaps with a CanActivate guard) to affect what module is loaded?

Update: I found this repo that seemed promising, but when implementing it I get the error: ERROR in Cannot read properties of undefined (reading 'loadChildren')



Solution 1:[1]

You can do it like this:

const routes: Routes = [
  {
    path: '',
    loadChildren: () =>
      someFlag === true
        ? import('./new.module').then(m => m.NewModule)
        : import('./legacy.module').then(m => m.LegacyModule)
  }
];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1