简体   繁体   中英

angular2-router-loader lazy loading webpack error

I have an Angular 2 project with webpack and I'm trying to implement a router with lazy loading:

import { NgModule }     from '@angular/core';
import { RouterModule } from '@angular/router';

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: '',
        loadChildren: './app/projects/projects.module#ProjectsModule',
      }
    ])
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule {}

To make this worked I tried to use angular2-router-loader . I followed the instructions and added it to the loaders in my webpack config.

module.exports = [
  {
    entry: {
      core: './node_modules/core-js/client/shim.min.js',
      zone: './node_modules/zone.js/dist/zone.js',
      reflect: './node_modules/reflect-metadata/Reflect.js',
      system: './node_modules/systemjs/dist/system.src.js'
    },
    output: {
      filename: './wwwroot/js/[name].js'
    },
    target: 'web',
    node: {
      fs: "empty"
    }
  },
  {
    entry: {
      app: './wwwroot/app/main.ts'
    },
    output: {
      filename: './wwwroot/app/bundle.js'
    },
    devtool: 'source-map',
    resolve: {
      extensions: ['', '.webpack.js', '.web.js', '.ts', '.js']
    },
    module: {
      loaders: [
        { 
          test: /\.ts$/,
          loaders: [
            'ts-loader',
            'angular2-router-loader'
          ]
        }
      ]
    }
  }];

But when I try to run webpack with this configuration I get the following error:

ERROR in ./wwwroot/app/app-routing.module.ts
Module build failed: TypeError: undefined is not a function
    at Object.module.exports.normalizeFilePath (/path/to/app/node_modules/angular2-router-loader/src/utils.js:54:16)
    at /path/to/app/node_modules/angular2-router-loader/src/index.js:56:22
    at String.replace (native)
    at Object.module.exports (/path/to/app/node_modules/angular2-router-loader/src/index.js:28:31)
 @ ./wwwroot/app/app.module.ts 16:27-58

Is there some additional setup I need to do?

  1. loadChildren should be relative path, if your AppRoutingModule in /app/ , the loadChildren should be ./projects/projects.module#ProjectsModule .

  2. output should have publicPath setting. output: { filename: './wwwroot/js/[name].js', publicPath: "/js/" }, angular2-router-loader will generate files for each modules as *.js , but webpack replace to wrong path. use publicPath setting let webpack know where is *.js root path.

  3. Recommend to use awesome-typescript-loader , that faster than ts-loader .

My github sample code for your reference:
https://github.com/johnwu1114/asp-net-core-angular-lazy-loading

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM