Angular 5延迟加载错误:找不到模块

Luc*_*ano 6 lazy-loading webpack angular-router-loader angular

我想使用延迟加载,但我不明白为什么它不起作用,它给我错误"找不到模块".
这是我的环境:
- Angular 5.2.1
- .NET Core 2
- Webpack 3.10.0
- angular-router-loader 0.8.2
- @ angular/cli 1.6.5
我在loadChildren尝试了不同的路径总是没有成功,我也暂时禁用所有警卫和儿童路线.我做错了什么?

FOLDERS

ClientApp
  app
    components
      users
        users-routing.module.ts
        users.module.ts
  app-routing.module.ts
  app.module.shared.ts
Run Code Online (Sandbox Code Playgroud)

APP-routing.module.ts

const appRoutes: Routes = [
    {
        path: 'users',
        loadChildren: './components/users/users.module#UsersModule'/* ,
        canLoad: [AuthGuard] */
    },
    {
        path: '',
        redirectTo: '/login',
        pathMatch: 'full'
    },
    {
        path: '**',
        redirectTo: '/login'
    }
];

@NgModule({
    imports: [
        RouterModule.forRoot(
            appRoutes,
            { enableTracing: false }
        )
    ],
    exports: [
        RouterModule
    ],
    providers: [
        CanDeactivateGuard
    ]
})
export class AppRoutingModule { }
Run Code Online (Sandbox Code Playgroud)

用户-routing.module.ts

const usersRoutes: Routes = [
    {
        path: '',
        component: UsersComponent/* ,
        //canActivate: [AuthGuard],
        children: [
            {
                path: 'detail',
                canActivateChild: [AuthGuard],
                children: [
                    {
                        path: ':id',
                        component: UserViewComponent
                    },
                    {
                        path: 'edit/:id',
                        component: UserFormComponent,
                        canDeactivate: [CanDeactivateGuard],
                        resolve: {
                            user: UsersResolver
                          }
                    },
                    {
                        path: '',
                        component: UserFormComponent,
                        canDeactivate: [CanDeactivateGuard]
                    }
                ]
            },
            {
                path: '',
                component: UsersListComponent
            }
        ] */
    }
];

@NgModule({
    imports: [
        RouterModule.forChild(
            usersRoutes
        )
    ],
    exports: [
        RouterModule
    ]
})
export class UsersRoutingModule { }
Run Code Online (Sandbox Code Playgroud)

users.module.ts

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        UsersRoutingModule,
        RouterModule
    ],
    declarations: [
        UsersComponent,
        UserFormComponent,
        UsersListComponent,
        UserViewComponent
    ],
    providers: [
        UsersResolver,
        RouterModule
    ]
})
export class UsersModule { }
Run Code Online (Sandbox Code Playgroud)

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AngularCompilerPlugin = require('@ngtools/webpack').AngularCompilerPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: {
            modules: false
        },
        context: __dirname,
        resolve: {
            extensions: ['.js', '.ts']
        },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [{
                    test: /\.ts$/,
                    include: /ClientApp/,
                    use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack'
                },
                {
                    test: /\.html$/,
                    use: 'html-loader?minimize=false'
                },
                {
                    test: /\.css$/,
                    use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize']
                },
                {
                    test: /\.(png|jpg|jpeg|gif|svg)$/,
                    use: 'url-loader?limit=25000'
                }
            ],
            loaders: [
                {
                  test: /\.ts$/,
                  loaders: [
                    'awesome-typescript-loader'
                  ]
                },
                {
                  test: /\.(ts|js)$/,
                  loaders: [
                    'angular-router-loader'
                  ]
                }
              ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: {
            'main-client': './ClientApp/boot.browser.ts'
        },
        output: {
            path: path.join(__dirname, clientBundleOutputDir)
        },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
            // Plugins that apply in production builds only
            new webpack.optimize.UglifyJsPlugin(),
            new AngularCompilerPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
                exclude: ['./**/*.server.ts']
            })
        ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: {
            mainFields: ['main']
        },
        entry: {
            'main-server': './ClientApp/boot.server.ts'
        },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AngularCompilerPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};  
Run Code Online (Sandbox Code Playgroud)

tsconfig.json

{
  "compilerOptions": {
    "module": "es2015",
    "moduleResolution": "node",
    "target": "es5",
    "sourceMap": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipDefaultLibCheck": true,
    "skipLibCheck": true, // Workaround for https://github.com/angular/angular/issues/17863. Remove this if you upgrade to a fixed version of Angular.
    "strict": true,
    "lib": [ "es6", "dom" ],
    "types": [ "webpack-env" ], 
    "typeRoots": [
      "node_modules/@types"
    ]
  },
  "exclude": [ "bin", "node_modules" ],
  "atom": { "rewriteTsconfig": false }
}
Run Code Online (Sandbox Code Playgroud)

错误信息

未处理的Promise拒绝:找不到模块'./ClientApp/app/components/users/users.module'.; 区域:角; 任务:Promise.then; 值:错误:找不到模块'./ClientApp/app/components/users/users.module'.在vendor.js V = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko:34015在ZoneDelegate.invoke(vendor.js V = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko:117428)在Object.onInvoke(vendor.js V = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko:5604)?在ZoneDelegate.invoke(vendor.js v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko:117427)在Zone.run(vendor.js v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko:117178)在vendor.js v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko:?117898在ZoneDelegate.invokeTask(vendor.js v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko:117461)在Object.onInvokeTask(在ZoneDelegate.invokeTask 5595)(vendor.js v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko:?vendor.js v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko?117460)在Zone.runTask(vendor.js v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko:117228)错误:无法找到模块" ./ClientApp/应用/组件/用户/ users.module".在http:// localhost:5000/dist/vendor.js?v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko:34015:9 ... [截断]

编辑

链接到stackblitz进行测试

Fra*_*erZ 16

我找到了两个解决方案(通过编辑VIA OP):

1)在使用import语句解析之后对模块的引用:

import { UsersModule } from './components/users/users.module';
Run Code Online (Sandbox Code Playgroud)

然后引用这种方式:

{
        path: 'users',
        loadChildren: () => UsersModule,
        canLoad: [AuthGuard]
}
Run Code Online (Sandbox Code Playgroud)

2)我已经在应用程序中添加了ng-router-loader(npm install ng-router-loader --save-dev),我以这种方式设置了webpack:

        rules: [{
                test: /\.ts$/,
                include: /ClientApp/,
                //use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack'
                use: isDevBuild ? [{ loader: 'ng-router-loader' }, 'awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack'
            },
            {
                test: /\.html$/,
                use: 'html-loader?minimize=false'
            },
            {
                test: /\.css$/,
                use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize']
            },
            {
                test: /\.(png|jpg|jpeg|gif|svg)$/,
                use: 'url-loader?limit=25000'
            }
        ],
Run Code Online (Sandbox Code Playgroud)

然后按路径引用模块:

    {
        path: 'users',
        loadChildren: './components/users/users.module#UsersModule',
        canLoad: [AuthGuard]
    }
Run Code Online (Sandbox Code Playgroud)

  • 但是用第一种方法,由于AOT在装饰器中不支持箭头功能,我无法再启用AOT。 (3认同)