angular2-router-loader延迟加载webpack错误

时间:2016-11-13 12:30:26

标签: angular webpack

我有一个带webpack的Angular 2项目,我试图实现一个延迟加载的路由器:

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 {}

为了实现这一点,我尝试使用angular2-router-loader。 我按照说明将其添加到我的webpack配置中的加载器中。

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'
          ]
        }
      ]
    }
  }];

但是当我尝试使用此配置运行webpack时,我收到以下错误:

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

我需要做一些额外的设置吗?

1 个答案:

答案 0 :(得分:0)

  1. loadChildren应该是相对路径,如果/app/中的AppRoutingModule,loadChildren应为./projects/projects.module#ProjectsModule

  2. 输出应设置为publicPath output: { filename: './wwwroot/js/[name].js', publicPath: "/js/" }, angular2-router-loader将为*.js生成每个模块的文件,但webpack会替换为错误的路径。使用publicPath设置让webpack知道*.js根路径在哪里。

  3. 建议使用awesome-typescript-loader,速度高于ts-loader

  4. 我的github示例代码供您参考:
    https://github.com/johnwu1114/asp-net-core-angular-lazy-loading