在 Angular 2 Webpack + AOT 设置中找不到模块 './sections/lazy/lazy.module.ngfactory' 错误

Cannot find module './sections/lazy/lazy.module.ngfactory' Error in Angular 2 Webpack + AOT setup

我一直在尝试让延迟加载的模块在简单的 AOT + Webpack Angular 2 设置中工作。

这是我的核心设置,如果有任何其他内容对创建更多上下文有用,请告诉我,我会更新问题。

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": false,
    "removeComments": true,
    "noLib": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["dom", "es6"],
    "sourceMap": true,
    "pretty": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitUseStrict": false,
    "noFallthroughCasesInSwitch": true,
    "moduleResolution": "node",
    "outDir": "build/tmp",
    "typeRoots": [
      "./node_modules/@types"
    ],
    "types": [
      "node",
      "jasmine"
    ]
  },
  "exclude": [
    "build",
    "dist",
    "node_modules",
    "src/main.aot.ts",
    "tmp"
  ],
  "angularCompilerOptions": {
    "debug": true,
    "genDir": "build",
    "skipMetadataEmit": true
  },
  "compileOnSave": false,
  "buildOnSave": false
}

app.routing.ts

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

export const routes: Routes = [
  { path: 'lazy', loadChildren: './sections/lazy/lazy.module#RecipesModule' },
];

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

webpack.prod.js

// ...
module: {
  rules: [
    {
      test: /\.ts$/,
      loader: '@ngtools/webpack',
    }
  ]
}
// ...
plugins: [
  // ...
  new AotPlugin({
    tsConfigPath: './tsconfig.json',
    entryModule: helpers.root('src/app/app.module#AppModule')
  }),
  // ...
]
// ...

构建过程顺利完成,但是当我尝试导航到 /lazy url.

时出现错误 Error: Uncaught (in promise): Error: Cannot find module './sections/lazy/lazy.module.ngfactory'.

另外 运行 development/JIT 中的应用程序可以正常运行。

你发现什么问题了吗?

谢谢

我通过删除我在 webpack 构建中使用的 ContextReplacementPlugin 解决了这个问题。

我的 webpack.config 文件中有以下 plugin 条目导致了问题:

// Workaround for angular/angular#11580
new ContextReplacementPlugin(
  // The (\|\/) piece accounts for path separators in *nix and Windows
  // https://github.com/angular/angular.io/issues/3514
  /angular(\|\/)core(\|\/)@angular/,
  helpers.root('src'), // location of your src
  {} // a map of your routes
),

我的项目配置基于 angular-starter repo,我可能没有正确使用 ContextReplacementPlugin 插件。