5

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?

1 Answer 1

5
+50

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

Sign up to request clarification or add additional context in comments.

4 Comments

@Drenai i also wasn't sure this is why i've tested before posting this answer. Have tried and it doesn't work?
thanks, seem works. moving dev route into environment config cause a Circular dependency developement.guard.ts -> src\environments\environment.ts -> developement.guard
@ar099968 why do you need guards there? as i understand its just for dev purposes
@Drenai I think this is correct behaviour since its ahead of time means it needs to load everything into memory and find dependencies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.