A:什么是HMR?
Q:HMR(热替换)用于在运行的应用程序中更新代码而不需要重建它。这将导致更快的更新和更少的全页重新加载。
创建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文件中配置HMR环境,并在构建和服务中添加配置以启用HMR。
Tip:<project-name>这里表示在angular.json中添加此配置的项目的名称。
"
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
"]
},
}
在终端中执行以下命令,即可将项目以hmr环境运行
ng serve --configuration hmr
或者在package.json文件中添加script对象,用来便捷启动程序:
"
scripts
": {
...
"
hmr
":
"
ng serve --configuration hmr
"
}
添加@ angurlarclass/HMR依赖
为了使HMR工作,我们需要安装依赖项并配置我们的应用程序来使用它,
$ npm install --save-dev @angularclass/hmr
创建
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));
}
以上步骤配置完成,终端执行hmr命令,
当在控制台中看到以下提醒时,说明hmr已经在工作啦~!
NOTICE Hot Module Replacement (HMR) is enabled for the dev server.