Search code examples
angularangular-cliproductionangular-cli-v7

Angular - How to exclude a lazy loaded module from prod build?


I have an angular module for demo purposes (DevShowcaseModule). This module should not be included in the production build. In order to hide this demos from the endusers and prevent demo code errors in the production.

Environment:

  • Angular Version: 7.2.5
  • Angular CLI: 7.3.2

This is my app-routing.module.ts

{
    path: APP_NAV_ITEMS.DEV_SHOWCASE,
    canActivate: [ AuthGuard ],
    loadChildren: './_dev-showcase/dev-showcase.module#DevShowcaseModule',
}

I have tried to exclude the module folder from the tsconfig.json. But it doesnt work, i can still call the route and the demo module is loaded.

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "importHelpers": true,
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,

    "noUnusedLocals": true,
    "noUnusedParameters": true,

    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "exclude": [
    "app/_dev-showcase/*"

  ]
}

Any idea how to do it properly?

Thanks!


Solution

  • I think you can leverage CLI fileReplacements feature like:

    angular.json

    "configurations": {
      "production": {
        "fileReplacements": [
          ...
          {
            "replace": "src/app/demo.routes.ts",
            "with": "src/app/demo.routes.prod.ts"
          }
        ],
    

    demo.routes.ts

    import { Routes } from '@angular/router';
    
    export const demoRoutes: Routes = [
      {
        path: 'demo',
        loadChildren: './demo/demo.module#DemoModule'
      }
    ];
    

    demo.routes.prod.ts

    export const demoRoutes = [];
    

    The root router configuration should look like:

    import { demoRoutes } from './demo.routes';
    
    RouterModule.forRoot([
      {
        path: '',
        component: HomeComponent
      },
      ...demoRoutes
    ])
    

    Using this method the cli will only bundle the DemoModule in dev mode.