angular - 热模块替换正在重新加载整个应用程序而不是特定组件

标签 angular hot-module-replacement

我创建了一个新的 Angular 项目并设置了 HMR,如下所述: https://github.com/angular/angular-cli/wiki/stories-configure-hmr

该项目包含具有 router-outlet 的主要组件(父组件)和指向延迟加载的 3 个子组件的链接。

注意:我也在使用自定义 RouteReuseStrategy,但据我测试,它对 HMR 没有影响。

无论我更改什么文件 - .html 或 .ts(父/子),整个应用程序都会重新加载。

我已经建立了一个基本的仓库,可以在这里找到: https://github.com/ronfogel/demo-hmr

最佳答案

这种行为是预料之中的,我将尝试解释发生了什么。

angular 设置的热模块替换实际上只是以更通用的方式重新引导整个应用程序并支持多个应用程序根目录,但是如果你把抽象放在一边,它只是简单地删除 app-root 标签,再次添加它并再次引导 AppModule ,所以整个应用程序改变了:

export const hmrBootstrap = (
  // webpack stuff
  module: any,
  // bootstrap is AppModule bootstrapper 
  bootstrap: () => Promise<NgModuleRef<any>>
) => {
  let ngModule: NgModuleRef<any>;
  module.hot.accept();
  // bootstraps AppModule ecery time a HMR is needed
  // sets ngModule equal to AppModule if successful (unnecessary)
  bootstrap().then(mod => (ngModule = mod));
  module.hot.dispose(() => {
    // next two lines get native element for all `app-root` tags
    // that exist in `index.html`
    const appRef: ApplicationRef = ngModule.injector.get(ApplicationRef);
    const elements = appRef.components.map(c => c.location.nativeElement);
    // I will share createNewHosts code below it's nothing fancy just
    // the simple add and delete i mentioned
    const makeVisible = createNewHosts(elements);
    //destroy the current AppModule and finalize deletion
    ngModule.destroy();
    makeVisible();
  });
};

关于angular - 热模块替换正在重新加载整个应用程序而不是特定组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52309317/

相关文章:

javascript - Uncaught Error : [HMR] Hot Module Replacement is disabled

configuration - webpack-dev-server 404 & 如何正确设置?

javascript - 热模块重新加载后 React 组件未从 Redux 状态更新

javascript - 无法在 Google Pay TEST 环境和订单总额中添加测试卡

字符串数组中的 Angular 双向数据绑定(bind)无法正常工作

javascript - 语法错误 : Unexpected token C in JSON at position 0 - Ionic 2 Http GET request

javascript - 热模块更换——更新但不重新渲染

javascript - 在 WebStorm 上的每个文件键上触发 React-native 热重载

angular - 在 Angular 中以动态 react 形式添加项目

html - 底部显示的 Angular 日期选择器