web-dev-qa-db-fra.com

Angular 5 chargement paresseux Erreur: Impossible de trouver le module

Je voudrais utiliser le chargement paresseux mais je ne peux pas comprendre pourquoi cela ne fonctionne pas, cela me donne l'erreur "Impossible de trouver le module".
Ceci est mon environnement:
- Angular 5.2.1
- .NET Core 2
- Webpack 3.10.0
- chargeur-chargeur-angulaire 0.8.2
- @ angular/cli 1.6.5
J'ai essayé différents chemins dans loadChildren toujours sans succès, j'ai également désactivé temporairement tous les gardes et le routage des enfants. Qu'ai-je fait de mal? 

DOSSIERS 

ClientApp
  app
    components
      users
        users-routing.module.ts
        users.module.ts
  app-routing.module.ts
  app.module.shared.ts

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

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

utilisateurs.module.ts 

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

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

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

MESSAGE D'ERREUR 

Rejet de la promesse non gérée: impossible de trouver le module "./ClientApp/app/components/users/users.module". ; Zone: angulaire; Tâche: Promise.then; Valeur: Erreur: Impossible de trouver le module './ClientApp/app/components/users/users.module'. at vendor.js? v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko: 34015 sur ZoneDelegate.invoke (vendor.js? v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko: 117428) sur Object.onInvoke (vendor.js? v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko: 5604) sur ZoneDelegate.invoke (vendor.js? v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko: 117427) sur Zone.run (vendor.js? v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko: 117178) at vendor.js? v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko: 117898 sur ZoneDelegate.invokeTask (vendor.js? v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko: 117461) à Object.onInvokeTask (vendor.js? v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko: 5595) sur ZoneDelegate.invokeTask (vendor.js? v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko: 117460) sur Zone.runTask (vendor.js? v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko: 117228) Erreur: Impossible de trouver le module './ClientApp/app/components/users/users.module'. at http: // localhost: 5000/dist/vendor.js? v = AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko: 34015: 9 ... [tronqué] 

MODIFIER 

lien vers stackblitz pour les tests

4
Luciano

J'ai trouvé deux solutions (VIA l'OP par edit):

1) référence au module après qu'il ait déjà été résolu avec une déclaration d'importation:

import { UsersModule } from './components/users/users.module';

puis en se référant de cette façon:

{
        path: 'users',
        loadChildren: () => UsersModule,
        canLoad: [AuthGuard]
}

2) J'ai ajouté ng-router-loader à l'application (npm installer ng-router-loader --save-dev) et j'ai configuré le WebPack de la manière suivante: 

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

puis en référençant le module par chemin:

    {
        path: 'users',
        loadChildren: './components/users/users.module#UsersModule',
        canLoad: [AuthGuard]
    }
11
FrankerZ

Habituellement, c'est une erreur avec le chemin. Changer le chemin.

Par exemple, cette solution fonctionne pour moi:

loadChildren: '../changelog/changelog.module#ChangelogModule'

./folder ou ../folder ou folder

0
Maxim Savin

essayez de faire votre user.module.ts:

import {UserRoutes } from './User.routing'

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        UsersRoutingModule.forChild(UserRoutes), //<-- for child
        RouterModule
    ],
    declarations: [
        UsersComponent,
        UserFormComponent,
        UsersListComponent,
        UserViewComponent
    ],
    providers: [
        UsersResolver,
        RouterModule
    ]
})
export class UsersModule { }
0
federico scamuzzi

Son nom de dossier de typo est Users pas users:

Changement

'./components/users/users.module#UsersModule'

à

'./components/Users/users.module#UsersModule'
0
Vivek Doshi