HMR(热替换)用于在运行的应用程序中更新代码而不需要重建它。这将导致更快的更新和更少的全页重新加载。
在environments文件夹中新建 src/environments/environment.hmr.ts,内容分别配置为:
export const environment = {
production: false,
hmr: true
}
将 src/environments/environment.prod.ts 中 设置属性hmr: false ,
export const environment = {
production: true,
hmr: false
};
将 src/environments/environment.ts 中 设置属性hmr: false ,
export const environment = {
production: false,
hmr: false
};
修改angular.json中的文件(之前的名字为angular-cli.json),代码中的projectName字段修改为你的项目名称
"build": {
"configurations": {
...
"hmr": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.hmr.ts"
}
]
}
}
},
...
"serve": {
"configurations": {
...
"hmr": {
"hmr": true,
"browserTarget": "<project-name>:build:hmr"
}
}
}
在 src/tsconfig.app.json中添加types必要的类型
{
...
"compilerOptions": {
...
"types": ["node"]
},
}
package.json文件中添加script对象,用来便捷启动程序:
"scripts": {
...
"hmr": "ng serve --configuration hmr"
}
为了使HMR工作,我们需要安装依赖项并配置我们的应用程序来使用它,
$ npm install --save-dev @angularclass/hmr
如果npm安装有问题请使用 yarn add 添加
创建 src/hmr.ts文件, 内容如下:
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();
});
};
将原src/main.ts中的内容替换如下,hmr就可以正常工作啦!!! :
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().catch(err => console.log(err));
}
安装完成之后执行 npm run hmr即可,看到控制台输出 NOTICE: Hot Module Replacement (HMR) is enabled for the dev server.即修改成功