延迟加载时找不到模块错误

Cannot find module error while Lazy loading

我想为我的模块设置延迟加载,但是有一个错误我无法解决。

错误是:

core.js:15724 ERROR Error: Uncaught (in promise): Error: Cannot find module 'app/invoice-builder/invoice-builder.module' Error: Cannot find module 'app/invoice-builder/invoice-builder.module'

app-routing.module.ts

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

const routes: Routes = [
  {
    path: 'invoice-builder',
    loadChildren : 'app/invoice-builder/invoice-builder.module#InvoiceBuilderModule'
  },
  {
    path: '**',
    redirectTo: 'invoice-builder'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { from } from 'rxjs';
import { MaterialModule } from './shared/material.module';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MaterialModule

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

我不明白这里发生了什么。我尝试了两次使用重新启动项目 npm start 但是,那没有用。任何帮助将不胜感激。

问题可能是由于您定义路径的方式所致。

来自官方 angular 文档 Lazy Loading Modules

Notice that the lazy loading syntax uses loadChildren followed by a string that is the relative path to the module, a hash mark or #, and the module’s class name.

尝试将您的路径更新为:

loadChildren : './app/invoice-builder/invoice-builder.module#InvoiceBuilderModule'

或者根据您的文件结构,您可能不需要 ./app,在这种情况下您可以尝试

loadChildren : './invoice-builder/invoice-builder.module#InvoiceBuilderModule'

像这样更新 LoadChieldren 路径,

loadChildren : './invoice-builder/invoice-builder.module#InvoiceBuilderModule'

因为 invoice-builder 文件夹在 app 文件夹中。 并且 app-routing.module.ts 也在同一个目录中,所以更新模块的路径。

我在使用 Angular 9 时遇到了类似的问题,并设法通过使用 found in docs:

的语法修复了它
const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  },
  {
    path: 'orders',
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  }
];