【问题标题】:Angular2 lazy loading module error 'cannot find module'Angular2延迟加载模块错误'找不到模块'
【发布时间】:2017-02-17 09:09:10
【问题描述】:

我试图为这个错误找到任何解决方案,但对我没有任何帮助。我有使用 Angular-CLI 创建的简单 Angular2 应用程序。当我在浏览器中提供此应用程序时,出现此错误:EXCEPTION: Uncaught (in promise): Error: Cannot find module '/app/test.module'. 我正在尝试在 loadChildren 中使用不同的路径:

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

文件夹

src/
  app/
    app-routing.module.ts
    app.component.ts
    app.module.ts
    test.component.ts
    test.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

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

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

堆栈跟踪

        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

【问题讨论】:

  • 尝试将loadChildren: '/app/test.module' 更改为loadChildren: 'app/test.module' 我猜这会起作用。
  • 我之前尝试过,但出现了同样的错误
  • 我整晚都被这个错误困扰。最后,我发现我只需要停止ng serve 命令,然后重新启动。然后错误消失了。因为模块会被延迟加载,所以在启动测试服务器的过程中可能会做一些工作。
  • @Mavlarn restart ng 也为我服务,谢谢!
  • @arthurr 你用ng build --aot 编译了吗?因为我只有在执行 --aot 时才会收到此错误,否则它可以正常工作

标签: angular module lazy-loading


【解决方案1】:

重启 ng serve 为我工作

【讨论】:

  • 我不断回到这个答案。我大喊“我又忘记了?!”在过去几个月中至少 5 次。
  • 我在 node_modules/.bin 目录中找不到该命令。
  • @zennin,如果你指的是ng serve,它是在终端输入的。此外,它特定于 Angular cli。如果您不使用 Angular cli,那么您将无法运行 ng serve。更多here.
  • @user3414799 我在使用--aot 编译时遇到此错误,您能帮帮我吗?
  • 我发誓,我什至记得重新启动它 - 但这就是它??‍♂️
【解决方案2】:

对于较新的 Angular 版本(10+?),延迟加载使用以下语法完成:

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

我在使用 Angular 4.4.5 和 webpack 时遇到了类似的问题,并设法在不使用字符串的情况下修复它,但使用模块类型引用(更容易编写且不易出错):

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

我找不到支持这种语法的 Angular(加载器)的最低版本。


一种可能适用于 AOT 的方法是将 lambda 语法替换为常规语法:

export function getTestModule() { return TestModule; }

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

同时检查this issue(感谢rey_coder)。

【讨论】:

  • 我更喜欢这个解决方案,但我不适合我。 ERROR in Error: Error encountered resolving symbol values statically. Reference to a local (non-exported) symbol 'appRoutes'. Consider exporting the symbol (position 8:7 in the original .ts file), resolving symbol AppRoutingModule
  • @Pascal - 你的模块是如何导出的?我只是在没有default 的情况下导出它:export class TestModule { }
  • @Alexei 怎么用,在 app.routes 中导入 TestModule 然后像loadChildren: () => TestModule 一样使用?我对我的应用程序进行了类似的操作,但是在错误中遇到了上述错误错误:错误遇到静态解析符号值。如果我用字符串做,我会得到cannot-find-module
  • @Sam - 不幸的是,你是对的。我必须在路径中使用loadChildren
  • 非常感谢!这帮助很大!你帮助我们摆脱了真正的痛苦!
【解决方案3】:

我也遇到过同样的问题。我通过以下两件事解决了它:

在根模块的路由配置中,使用loadChildren 和延迟加载的角度模块的相对路径。字符串用 # 分隔,其中 split 的右侧是延迟加载模块的类名。

我已将 ./ 作为前缀添加到 loadChildren 字符串。

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

我正在使用 webpack 2,它需要一个用于 Angular 2 的加载器,它支持使用 Angular 路由器加载基于字符串的模块。将此添加到项目中

yarn add angular-router-loader -D

然后将angular-router-loader 添加到打字稿加载器

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

它对我有用。

【讨论】:

  • 我还必须省略 app 部分:{ path:'user', loadChildren:'./user/user.module#UserModule'}
  • @Jasnan 在哪里添加这个loaders,我不知道是哪个文件
  • @NikhilRadadiya loaderswebpack.config.js 文件中。但是如果你使用angular-cli,除非你使用ng eject,否则你不会有这个文件,但不建议在使用angular-cli构建的项目中使用它
【解决方案4】:

对于使用最近的 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 { }

另一种方式(不在顶部进行导入):

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

【讨论】:

  • 第一种方式,真的需要吗?在我看来,从未使用过 TestMudule ...正在工作的导入是 () => import
  • 所有答案都解决了我的问题,不是 ng serve restart 也不是相对路径。赞成,因此这将成为公认的答案。
  • 在 Angular 9 中,这解决了我的问题!我使用了第二个版本,顶部没有导入。非常感谢分享!
【解决方案5】:

最后我发现我需要通过这种方式在路由配置中导入延迟加载的模块:

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

模块路径前没有任何/./

【讨论】:

  • 其实两者都有效,还需要保持这样的路径+restart ng serve
  • 这个答案对我有用。但不是重启 ng-serve 答案。
  • 我发现完全相反,./ 为我工作而不是应用程序
  • 删除 ./ 并添加 app/ 在 Angular CLI 项目中为我工作。
【解决方案6】:

在 Angular 9 中,我这样做了,它对我有用: loadChildren: () => import('./items/items.module').then(m => m.ItemsModule)

你可以去official documentation看看

【讨论】:

    【解决方案7】:

    我改了

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

    为此

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

    解决了我的问题。

    【讨论】:

    • 谢谢!这是唯一对我有用的东西!
    【解决方案8】:

    它对我有用。

    ../app/

    我通过使用 VS 代码中的建议弹出窗口解决了这个问题。你可以 也遵循这一点。无需去任何地方。 (我认为,路径可能会有所不同 每个项目。)

    【讨论】:

      【解决方案9】:

      在我刚刚接手的一个项目中,我已经解决了几个小时的问题。以上解决方案都不起作用,但后来我意识到所有延迟加载的模块都有 .ts 扩展名。

      如果其他人有问题,请检查您是否需要将loadChildren: 'app/example.module.ts' 更改为loadChildren: 'app/example.module'

      【讨论】:

        【解决方案10】:

        在通过延迟加载模块将不同功能(例如 test.module.ts)与其根应用程序(例如 app.module.ts)分离的用例场景中,我们可以创建测试模块及其组件在子文件夹中(例如 src/app/test/)。 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);
        

        “父”模块 (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);
        

        这允许命令式加载的根应用程序和入口组件随后在需要时从 test.module.ts 延迟加载特性。

        【讨论】:

          【解决方案11】:

          确保包括 从'@angular/router'导入{路由,RouterModule}; 在模块中延迟加载

          【讨论】:

            【解决方案12】:

            我遇到了类似的问题。我刚刚重新启动服务器,它工作。 :)

            【讨论】:

              【解决方案13】:

              我已经解决了我自己的问题。不要将.ts 放在路径名中。不要使用'path/to/my/module.ts#MyModuleClass',而是使用'path/to/my/module#MyModuleClass'

              【讨论】:

                【解决方案14】:

                在我的情况下,路径与我在其他地方声明的路径共享相同的路径,假设它们是相对路径。比如下面的

                不工作

                管理模块

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

                用户模块

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

                单独地,当只声明一个时,它们工作正常,但不能一起使用,因为它抱怨 ./organisation/organisation.module 路径,我将两者都更改为下面的模式并且没关系。

                工作

                管理模块

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

                用户模块

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

                【讨论】:

                  【解决方案15】:

                  你需要改变

                  export default class TestModule { }
                  

                  export class TestModule { }
                  

                  这应该可以解决您的问题

                  【讨论】:

                    【解决方案16】:

                    在我的项目中,我通过将相对路径更改为从 src 开始解决了这个问题

                    所以而不是

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

                    我改成:

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

                    文件夹结构是:

                    【讨论】:

                      猜你喜欢
                      • 2017-09-03
                      • 1970-01-01
                      • 2021-01-05
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2017-08-21
                      • 2020-12-19
                      • 2018-05-22
                      相关资源
                      最近更新 更多