简体   繁体   English

Angular2 延迟加载模块错误“找不到模块”

[英]Angular2 lazy loading module error 'cannot find module'

I was trying to find any solution for this error but nothing works for me.我试图为这个错误找到任何解决方案,但对我来说没有任何作用。 I have simple Angular2 App created with Angular-CLI.我有一个使用 Angular-CLI 创建的简单 Angular2 应用程序。 When I serve this app in browser I'm getting this error: EXCEPTION: Uncaught (in promise): Error: Cannot find module '/app/test.module'.当我在浏览器中提供此应用程序时,我收到此错误: EXCEPTION: Uncaught (in promise): Error: Cannot find module '/app/test.module'. I was trying using different path in loadChildren:我试图在 loadChildren 中使用不同的路径:

'/app/test.module'
'./app/test.module'
'./test.module'
'/src/app/test.module'

Folders文件夹

src/
  app/
    app-routing.module.ts
    app.component.ts
    app.module.ts
    test.component.ts
    test.module.ts

app.module.ts app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { RoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts app-routing.module.ts

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


const routes: Routes = [
  { path: '', loadChildren: '/app/test.module' }
];

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

test.module.ts测试模块.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { TestComponent } from './test.component';

export const routes: Routes = [
    { path: '', component: TestComponent }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  exports: [TestComponent],
  declarations: [TestComponent]
})
export default class TestModule { }

stack trace堆栈跟踪

        error_handler.js:45EXCEPTION: Uncaught (in promise): Error: Cannot find module '/app/test.module'.ErrorHandler.handleError @ error_handler.js:45next @ application_ref.js:273schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:120onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
    2016-10-08 14:22:50.612 error_handler.js:50ORIGINAL STACKTRACE:ErrorHandler.handleError @ error_handler.js:50next @ application_ref.js:273schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:120onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
    2016-10-08 14:22:50.613 error_handler.js:51Error: Uncaught (in promise): Error: Cannot find module '/app/test.module'.
        at resolvePromise (zone.js:429)
        at zone.js:406
        at ZoneDelegate.invoke (zone.js:203)
        at Object.onInvoke (ng_zone_impl.js:43)
        at ZoneDelegate.invoke (zone.js:202)
        at Zone.run (zone.js:96)
        at zone.js:462
        at ZoneDelegate.invokeTask (zone.js:236)
        at Object.onInvokeTask (ng_zone_impl.js:34)
        at ZoneDelegate.invokeTask (zone.js:235)ErrorHandler.handleError @ error_handler.js:51next @ application_ref.js:273schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:120onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
    2016-10-08 14:22:50.614 zone.js:355Unhandled Promise rejection: Cannot find module '/app/test.module'. ; Zone: angular ; Task: Promise.then ; Value: Error: Cannot find module '/app/test.module'.(…) Error: Cannot find module '/app/test.module'.
        at webpackEmptyContext (http://localhost:4200/main.bundle.js:49550:8)
        at SystemJsNgModuleLoader.loadAndCompile (http://localhost:4200/main.bundle.js:57952:40)
        at SystemJsNgModuleLoader.load (http://localhost:4200/main.bundle.js:57945:60)
        at RouterConfigLoader.loadModuleFactory (http://localhost:4200/main.bundle.js:22354:128)
        at RouterConfigLoader.load (http://localhost:4200/main.bundle.js:22346:81)
        at MergeMapSubscriber.project (http://localhost:4200/main.bundle.js:61105:111)
        at MergeMapSubscriber._tryNext (http://localhost:4200/main.bundle.js:32515:27)
        at MergeMapSubscriber._next (http://localhost:4200/main.bundle.js:32505:18)
        at MergeMapSubscriber.Subscriber.next (http://localhost:4200/main.bundle.js:7085:18)
        at ScalarObservable._subscribe (http://localhost:4200/main.bundle.js:48555:24)consoleError @ zone.js:355_loop_1 @ zone.js:382drainMicroTaskQueue @ zone.js:386
    2016-10-08 14:22:50.620 zone.js:357Error: Uncaught (in promise): Error: Cannot find module '/app/test.module'.(…)consoleError @ zone.js:357_loop_1 @ zone.js:382drainMicroTaskQueue @ zone.js:386

重新启动ng serve对我有用

For newer Angular versions (10+?) lazy loading is done using the following syntax:对于较新的 Angular 版本(10+?),延迟加载使用以下语法完成:

{ path: "foos", loadChildren: () => import ("./foos/foo.module").then(m => m.FooModule) },

I met a similar issue when working with Angular 4.4.5 and webpack and managed to fix it without using strings, but module type reference (much easier to write and less error prone):我在使用 Angular 4.4.5 和 webpack 时遇到了类似的问题,并设法在不使用字符串的情况下修复了它,但模块类型引用(更容易编写且不易出错):

const routes: Routes = [
  { path: '', loadChildren: () => TestModule }
];

I could not find the minimum version for Angular (loader) the supports this syntax.我找不到支持此语法的 Angular(加载程序)的最低版本。


A way that might work with AOT is to replace lambda syntax with a regular one:一种可能适用于 AOT 的方法是用常规语法替换 lambda 语法:

export function getTestModule() { return TestModule; }

const routes: Routes = [
  { path: '', loadChildren: getTestModule }
];

Also check this issue (thanks to rey_coder ).还要检查这个问题(感谢rey_coder )。

I have faced this same issue.我也遇到过同样的问题。 I solved it by doing following 2 things:我通过做以下两件事来解决它:

In root module's route configuration, use loadChildren with a relative path to the lazy loaded angular module.在根模块的路由配置中,使用loadChildren和延迟加载的 angular 模块的相对路径。 The string is delimited with a # where the right side of split is the lazy loaded module's class name.该字符串以 # 分隔,其中 split 的右侧是延迟加载模块的类名。

I have added ./ as prefix to the loadChildren string.我在loadChildren字符串中添加了 ./ 作为前缀。

{ path:'user', loadChildren:'./app/user/user.module#UserModule'}

I am using webpack 2 and it needs a loader for Angular 2 that enables string-based module loading with the Angular Router.我正在使用 webpack 2,它需要一个用于 Angular 2 的加载器,该加载器支持使用 Angular 路由器加载基于字符串的模块。 Add this to the project将此添加到项目中

yarn add angular-router-loader -D

then add the angular-router-loader to typescript loaders然后将angular-router-loader添加到 typescript loader

loaders: [
  {
    test: /\.ts$/,
    loaders: [
    'awesome-typescript-loader',
    'angular-router-loader'
    ]
  }
]

and its working for me.它对我有用。

For people who are using a recent Angular version (v9 in my case), you can setup your route with the following syntax declaration:对于使用最新 Angular 版本(在我的情况下为 v9)的人,您可以使用以下语法声明设置您的路线:

import { TestModule } from './modules/test.module';
const appRoutes: Routes = [
  { path: 'blogs', loadChildren: () => import('./modules/test.module').then(m => m.TestModule) },
];

// NgModule
// declarations
// imports
// providers
// bootstrap

export class AppModule { }

Another way (without making the import at the top):另一种方式(无需在顶部进行导入):

    const appRoutes: Routes = [
      { path: 'blogs', loadChildren: () => import('./modules/test.module').then(m => m.TestModule) },
    ];

Finally I found out that I need to import lazy loaded module in routing config this way:最后我发现我需要通过这种方式在路由配置中导入延迟加载模块:

const routes: Routes = [
   { path: '', loadChildren: 'app/test.module' }
];

without any / or ./ in front of module path.模块路径前没有任何/./

In Angular 9 I did this and it worked for me: loadChildren: () => import('./items/items.module').then(m => m.ItemsModule)在 Angular 9 中,我这样做了,它对我loadChildren: () => import('./items/items.module').then(m => m.ItemsModule)loadChildren: () => import('./items/items.module').then(m => m.ItemsModule)

You can have a look on official documentation你可以看看官方文档

I change this我改变这个

{
            path: 'test',
            loadChildren: 'app/tests/test.module#TestModule'

}

for this为此

   {
        path: 'test', loadChildren: () => new Promise(resolve => {
            (require as any).ensure([], require => {
                resolve(require('app/tests/test.module').TestModule);
            })
        })
    },

And solved my problem.并解决了我的问题。

It was worked for me by using.它通过使用对我有用。

../app/

I solved this issue by using the suggestion popup in VS code.我通过在 VS 代码中使用建议弹出窗口解决了这个问题。 You can also follow that.你也可以按照那个。 No need to go anywhere.无需去任何地方。 (I Think, the path may vary in every project.) (我认为,每个项目的路径可能会有所不同。)

I've been troubleshooting this for aa couple of hours on a project I've just taken over from.在我刚刚接手的一个项目上,我已经解决了几个小时的问题。 None of the above solutions were working, but then I realised that all the lazy-loaded modules had the .ts extension.上述解决方案都不起作用,但后来我意识到所有延迟加载的模块都有 .ts 扩展名。

If anyone else is having issues, check if you need to change loadChildren: 'app/example.module.ts' to loadChildren: 'app/example.module' .如果其他人遇到问题,请检查您是否需要将loadChildren: 'app/example.module.ts'更改为loadChildren: 'app/example.module'

In a use-case scenario to segregate a distinct feature (eg test.module.ts) from its root application (ie app.module.ts) through a lazily-loaded module, we could create the test module and it's components in a sub-folder (eg src/app/test/).在用例场景中,通过延迟加载的模块将不同的功能(例如 test.module.ts)与其根应用程序(即 app.module.ts)分离,我们可以在子中创建测试模块及其组件- 文件夹(例如 src/app/test/)。 The test-routing.module could be configured this way: test-routing.module 可以这样配置:

//test-routing.module.ts
//routes to test.component.ts as an example

import { Routes, RouterModule } from '@angular/router';
import { TestComponent } from './test.component';

const feature_test_routes: Routes = [

    { 
        path: '',
        component: TestComponent
    }

];

export const TestRoutingModule = RouterModule.forChild(feature_test_routes);

The "parent" module (app-routing.module.ts), would have a route that looks like this: “父”模块 (app-routing.module.ts) 的路由如下所示:

//app-routing.module.ts
//routes to http://localhost:4200/test

import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
const root_routes: Routes = [

    { 
        path: '',
        component: AppComponent, 
        children: [
            {
                path: 'test',
                loadChildren: './test/test.module#TestModule'
            }
        ]
    }

];

export const AppRoutingModule = RouterModule.forChild(root_routes);

This allows the root application and entry component, imperatively loaded, to subsequently lazy-load features from test.module.ts as a child when needed.这允许命令式加载的根应用程序和入口组件随后在需要时将 test.module.ts 中的功能作为子项进行延迟加载。

make sure to include import { Routes, RouterModule } from '@angular/router';确保包含 import { Routes, RouterModule } from '@angular/router'; in the module to load lazely在模块中延迟加载

I had a similar issue.我有一个类似的问题。 I just restarted the server and it worked.我刚刚重新启动了服务器,它工作正常。 :) :)

I have solved my own issue.我已经解决了我自己的问题。 Don't put the .ts in the path name.不要将.ts放在路径名中。 Rather than using 'path/to/my/module.ts#MyModuleClass' , use 'path/to/my/module#MyModuleClass'而不是使用'path/to/my/module.ts#MyModuleClass' ,使用'path/to/my/module#MyModuleClass'

In my case the path shared the same route as one I declared elsewhere, assuming they would be relative paths.就我而言,该路径与我在其他地方声明的路径共享相同的路径,假设它们是相对路径。 eg like below in the例如像下面

Not Working不工作

Admin Module管理模块

    {
    path: 'organisation',
    canActivate: [AuthGuard],
      loadChildren: './organisation/organisation.module#AdminOrganisationModule',
    },

User Module用户模块

    {
    path: 'organisation',
    canActivate: [AuthGuard],
      loadChildren: './organisation/organisation.module#UserOrganisationModule',
    },

individually, when only one was declared, these were working fine, but not together as it complained about the ./organisation/organisation.module path , I changed both to the pattern below and it was ok.单独地,当只声明一个时,这些工作正常,但不能一起工作,因为它抱怨 ./organisation/organisation.module 路径,我将两者都更改为下面的模式,没问题。

Working工作

Admin Module管理模块

    {
    path: 'organisation',
    canActivate: [AuthGuard],
      loadChildren: '../admin/organisation/organisation.module#AdminOrganisationModule',
    },

User Module用户模块

        {
    path: 'organisation',
    canActivate: [AuthGuard],
      loadChildren: '../user/organisation/organisation.module#UserOrganisationModule',
    },

You need to change你需要改变

export default class TestModule { }

to

export class TestModule { }

That should fix your problems那应该可以解决您的问题

in my project i resolved the issue by changing the relative path to start from src在我的项目中,我通过将相对路径更改为从src开始解决了该问题

so instead of所以而不是

loadChildren: () => import('./user/user.module') .then(m => m.UserModule)

I changed to:我改为:

loadChildren: () => import('./src/app/user/user.module') .then(m => m.UserModule)

Folder structure was:文件夹结构是: 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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