更新后的 Hmr 问题 Angular

Hmr issues after update Angular

我正在使用一些遗留代码,我决定将其更新为 Angular9。我已经解决了大部分其他问题,但我仍然被一些 HMR 抛出的错误所困扰代码。

 src/main.ts:16:7 - error TS2591: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.

16   if (module['hot']) {
         ~~~~~~
src/main.ts:17:18 - error TS2591: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.

17     hmrBootstrap(module, bootstrap);

说找不到模块类型。我发现的其他答案说删除所有 nodule_modules 并重新安装,将 [nodes] 添加到类型,或在 tsconfig 中更改 { environments } 的导入,但所有这些似乎都是正确的,所以我不完全确定为什么找不到模块。这段代码在 Angular 5.2 中工作,一定是一路上搞砸了。

我扫描了一些文件,这是我找到的

import { enableProdMode } from "@angular/core";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";

import { AppModule } from "./app/app.module";
import { environment } from "./environments/environment";

import { hmrBootstrap } from "./hmr";

if (environment.production) {
  enableProdMode();
}

const bootstrap = () => platformBrowserDynamic().bootstrapModule(AppModule);

if (environment.hmr) {
  if (module['hot']) {
    hmrBootstrap(module, bootstrap);
  } else {
    console.error("HMR is not enabled for webpack-dev-server!");
    console.log("Are you using the --hmr flag for ng serve?");
  }
} else {
  bootstrap();
}

import { NgModuleRef, ApplicationRef } from "@angular/core";
import { createNewHosts } from "@angularclass/hmr";

export const hmrBootstrap = (
  module: any,
  bootstrap: () => Promise<NgModuleRef<any>>
) => {
  let ngModule: NgModuleRef<any>;
  module.hot.accept();
  bootstrap().then(mod => (ngModule = mod));
  module.hot.dispose(() => {
    const appRef: ApplicationRef = ngModule.injector.get(ApplicationRef);
    const elements = appRef.components.map(c => c.location.nativeElement);
    const makeVisible = createNewHosts(elements);
    ngModule.destroy();
    makeVisible();
  });
};
{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": [
      "nodes"
    ]
  },
  "files": [
    "main.ts",
    "polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

我处理这个问题已经有一段时间了,非常感谢您的帮助。谢谢!

认为可以通过在 files 部分添加对 tsconfig.app.json 文件的引用来解决此问题。指向您的 typings.d.ts 文件。

例如

"files": [
    "typings.d.ts",

这是因为在 Angular 9 更新中他们有

...updated the tsconfig.app.json to limit the files compiled. If you rely on other files being included in the compilation, such as a typings.d.ts file, you need to manually add it to the compilation.

您的 tsconfig.app.json 文件中有错字。要添加的正确类型是 node 而不是 nodes:

{
  ...
  "types": [
    "node"
  ]
  ...