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

2023-11-25

我想使用延迟加载,但我不明白为什么它不起作用,它给了我错误“找不到模块”。
这是我的环境:
- 角度 5.2.1
- .NET核心2
- 网页包 3.10.0
- 角度路由器加载器 0.8.2
- @角度/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

应用程序路由.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 { }

用户路由.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 { }

用户.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 }
}

错误信息

未处理的 Promise 拒绝:找不到模块 './ClientApp/app/components/users/users.module'。 ;区域:有角; 任务:Promise.then;值:错误:找不到模块 './ClientApp/app/components/users/users.module'。 在供应商.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) 在供应商.js?v=AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko:117898 在 ZoneDelegate.invokeTask (vendor.js?v=AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko:117461) 在 Object.onInvokeTask (vendor.js?v=AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko:5595) 在 ZoneDelegate.invokeTask (vendor.js?v=AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko:117460) 在 Zone.runTask (vendor.js?v=AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko:117228) 错误:找不到模块 './ClientApp/app/components/users/users.module'。 在http://localhost:5000/dist/vendor.js?v=AdjSBPSITyauSY4VQBBoZmJ6NdWqor7MEuHgdi2Dgko:34015:9...[截断]

EDIT

链接到 stackblitz 进行测试


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

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

    从'./components/users/users.module'导入{UsersModule};

然后这样引用:

{
    path: 'users',
    loadChildren: () => UsersModule,
    canLoad: [AuthGuard]
}
  1. 我已经添加了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'
             }
         ],
    

然后通过路径引用模块:

    {
        path: 'users',
        loadChildren: './components/users/users.module#UsersModule',
        canLoad: [AuthGuard]
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 5 延迟加载错误:找不到模块 的相关文章

随机推荐

  • android中如何获取Webview的宽度和高度

    我想确定的宽度和高度WebView 我已经尝试过使用 webView getWidth webView getHeight 但生成的日志始终显示它们为 0 这是一个更优雅的解决方案 public void onCreate Bundle s
  • ES6中扩展类时是否可以定义回调

    本质上 如果我的库类被调用 我想做一些设置工作 例如 class Child extends Parent methods 我想分配一个在扩展父类时调用的函数 我希望以某种方式得到通知 在它即将发生之前 使用要作为参数附加的方法 或在使用
  • 无法在 Android NDK 中包含像矢量这样的 C++ 标头

    当我尝试在我的 Android NDK 项目中包含任何 C 类 例如向量 时 使用最新的 NDK r5b 我收到如下错误 Compile thumb test libstl lt test libstl cpp Users nitrex88
  • CSS 过渡忽略宽度

    我有一个显示为块的标签 页面加载时 其宽度会增加 css动画片从零到包含 div 的某个百分比 小提琴包含一个 MWE 但此 div 中有多个链接 每个链接都有不同的宽度 悬停时 我希望它使用 CSS 改变颜色 改变背景颜色 并扩展到 di
  • 去替换所有字符串

    我阅读了示例代码golang org 网站 本质上 代码如下所示 re regexp MustCompile a x b fmt Println re ReplaceAllString ab axxb T fmt Println re Re
  • CSS:在 CSS 中设置背景图像

    在 CSS 中设置背景图像时 正确的语法是什么 在Visual Studio中 自从出现以来 后台似乎没有任何问题 但在IE或FF等浏览器中 背景不会出现 我在这里错过了什么吗 我使用的语法如下 我认为是正确的 headerArea hei
  • Xerces-C:从 v2.x 迁移到 v3.x?

    我想将一个项目 我不太熟悉的遗留代码 从 Xerces C v2 x 迁移到 v3 x 事实证明 Xerces C v3 删除了 DOMBuilder 类 这迁移档案告诉我这个 作为最终 DOM Level 3 规范一致性工作的一部分 许多
  • Django post_save() 信号实现

    我有一个关于 django 的问题 我这里有ManyToMany模型 class Product models Model name models CharField max length 255 price models DecimalF
  • 如何将数据类型 CLOB 更改为 VARCHAR2(sql)

    表 客户 ID NAME DATATYPE NUMBER VARCHAR2 100 CLOB 我想改变DATA专栏来自CLOB到 VARCHAR2 1000 我已经尝试过ALTER TABLE customers MODIFY DATA V
  • 如何使用键值删除字典数组中的对象

    我有一个字典数组 如下所示 photo id 255025344921316 photo url https scontent xx fbcdn net v t1 0 0 p320x320 16143181 255025344921316
  • React 如何使用 TypeScript 在 Textfield Material-UI 中使用图标

    我使用 TypeScript Material UI 和 Formik 设计了一个带有验证的表单 我想要一个材质 UI 图标出现在我的文本字段区域中 这是我的代码 import React from react import Formik
  • 惰性变量定义后括号做什么?

    我正在分析一些第三方代码 有一个看起来像这样的 惰性 var 语句 我想了解 计算属性 大括号后面的括号在做什么 lazy var defaults NSUserDefaults return standardUserDefaults re
  • asp.net mvc 和 css:使菜单选项卡在选择时保持突出显示

    有一个更好的方法吗 我有一个 HTML 帮助器扩展方法 它检查当前选项卡菜单是否是选定的菜单 然后选择 selected css 类 我将 html IsSelected 链接放在每个 li 中 li class 其中 a 是选项卡名称 b
  • 批量 C# 数据表到 postgresql 表

    我有一个包含数千条记录的数据表 我有一个与数据表具有相同字段的 postgres 表 我想每天截断该表并再次填充数据表的数据 我见过sql批量复制 但它在postgres上不可用 那么 哪一种方法是最有效的呢 每条记录一次插入 多次插入 插
  • 结构类型嵌入字段访问

    我在尝试学习golang目前我正在尝试理解指针 我定义了三种结构类型 type Engine struct power int type Tires struct number int type Cars struct Engine Tir
  • stdout 在 docker 容器中缓冲

    我不完全确定这里发生了什么 但当我在容器中运行代码时 stdout 似乎正在被缓冲 但如果我在主机或 OSX 上运行它 则不会 https github com myles mcdonnell procwrap blob master pr
  • 如何在 clojure 中创建可执行文件?

    我一直在使用 Clojure Box 在 REPL 环境中学习 clojure 如何制作可执行文件 jar 我想知道这样的事情是否可能 在记事本上编写 clojure 代码并将其命名为project clj 编译项目 clj 获取可执行文件
  • 如何创建 Gmail API 消息

    我想使用 Google 的 Gmail API 发送消息 我已成功通过身份验证 并尝试使用 GmailService 发送消息 我想用这个 myService Users Messages Send myMessage me Execute
  • iPhone:如何获取当前毫秒数?

    获取当前系统时间毫秒的最佳方法是什么 如果您正在考虑将其用于相对计时 例如游戏或动画 我宁愿使用CA当前媒体时间 double CurrentTime CACurrentMediaTime 这是推荐的方式 NSDate从网络同步时钟获取 并
  • Angular 5 延迟加载错误:找不到模块

    我想使用延迟加载 但我不明白为什么它不起作用 它给了我错误 找不到模块 这是我的环境 角度 5 2 1 NET核心2 网页包 3 10 0 角度路由器加载器 0 8 2 角度 cli 1 6 5我在 loadChildren 中尝试了不同的