Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: lazy loading module only for dev (environment.production === false)

Tags:

angular

I have a lazy loaded module only for development purpose and i want don't deploy it into the production build.

With a guard i have denied the activation and the loading:

const routes: Routes = [
  {
    path: 'dev',
    loadChildren: './features/dev/dev.module#DevModule',
    canActivate: [DevelopmentGuard],
    canLoad: [DevelopmentGuard]
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

the guard:

@Injectable({
  providedIn: 'root'
})
export class DevelopmentGuard implements CanActivate, CanLoad {

  constructor() {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return this.can();
  }

  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return this.can();
  }

  canLoad(route: Route, segments: UrlSegment[]): boolean {
    return this.can();
  }

  private can(): boolean {
    return (environment.production === false);
  }
}

it works, my dev module works only in dev, but the scripts of the dev module are in the build.

There is a way for totally remove the script from the build of the prod version?

like image 888
ar099968 Avatar asked Apr 24 '19 15:04

ar099968


1 Answers

option 1

let routes: Routes = []; // provide default rotes

if(!environment.production){
   routes = [...routes, [  {
    path: 'dev',
    loadChildren: './features/dev/dev.module#DevModule',
    canActivate: [DevelopmentGuard],
    canLoad: [DevelopmentGuard]
  },
]]
}

Options 2.

export let devRoutes: Routes = [];

if(!environment.production){
   devRoutes = [  {
    path: 'dev',
    loadChildren: './features/dev/dev.module#DevModule',
    canActivate: [DevelopmentGuard],
    canLoad: [DevelopmentGuard]
  }
 ]
}

RouterModule.forRoot([...routes, ...devRoutes])

With option 2 you can make it even better if you move devRoutes to environment config

like image 179
Vova Bilyachat Avatar answered Oct 21 '22 19:10

Vova Bilyachat