Error when trying to lazy load feature modules using angular-cli with webpack

后端 未结 4 632
旧时难觅i
旧时难觅i 2020-12-31 18:49

Hi I\'m trying to use angular-cli with webpack (+productivity) to build my angular2 app but I\'m having issues when trying to lazy load modules which were working with versi

相关标签:
4条回答
  • 2020-12-31 19:38

    I have another solution :

    on your app.routers.ts create a function like that :

    let loadAoTModule = (path, module) => {
    
      let result = () => new Promise(function (resolve) {
        (require as any).ensure([], function (require: any) {
          resolve(require(path)[module]);
        });
      });
    
      return result;
    }
    
    const routes: Routes = [
      { path: '', redirectTo: 'customer', pathMatch: 'full'},
    
      { path          : 'customer'  ,
        // for a file locate on 'src/app/customer/customer.module'
        // and a module 'CustomerModule'
        loadChildren  :  loadAoTModule('./customer/customer.module', 'CustomerModule')
    
      }
    ];
    

    work fine for me.

    0 讨论(0)
  • 2020-12-31 19:46

    There's a loader for this (angular2-router-loader). However you can't use it with the CLI without hacking the config. Luckily, es6-promise-loader does work with the CLI out-of-the-box.

    This is what worked out for me:

    First we'll need the es6-promise-loader:

    npm i --save-dev es6-promise-loader

    Then define your route like this:

    {path:"lazy", loadChildren: () => require('es6-promise!./path/to/module')('ClassName')}

    the es6-promise-loader replaces the above with this:

    loadChildren: () => new Promise(function (resolve) {
            require.ensure([], function (require) {
              resolve(require('./path/to/module')['ClassName']));
            });
          });
    

    which is the proper way to load a module with webpack, but cumbersome to put into every route.

    0 讨论(0)
  • 2020-12-31 19:47

    Angular-cli changed the build system between beta.10 and beta.14, from SystemJS to Webpack.

    I tried using lazy loading with angular-cli(beta.17) and it worked for me.

    As per my understanding,

    SystemJs - we need to give full path for lazy loading Ex: ./app/dashboard/dashboard.module#DashboardModule

    Webpack - we need to give relative path for lazy loading Ex: ./dashboard/dashboard.module#DashboardModule

    Note : Don't forget to restart the server to see the changes reflecting.(ng serve)

    This minor observation fixed my issue. Please see if this is useful or correct me on anything.

    0 讨论(0)
  • 2020-12-31 19:55

    Use import to load the module dynamically. Remember to add "module": "esNext", in the tsconfig file.

    loadChildren: () => import('projects/Reservation/src/app/app.module').then((m: any) => m.AppModule),
    

    AppModule is the class name of the module.

    0 讨论(0)
提交回复
热议问题