最近在学习使用脚手架配置一个angular写一个小项目,过程中用到了热加载,热加载能够很好的提高我们的开发效率。
配置前准备:已经通过脚手架新建一个angular项目,并且安装了hmr依赖。
npm i --save-dev @angularclass/hmr1. src/environments 目录下面添加一个配置文件 environment.hmr.ts
export const environment = {
production: false,
hmr: true
};2. 在 environment.prod.ts 和 environment.ts 两个文件中添加 hmr:false
3. 在 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();
});
};4. 修改一下 angular.json 文件
找到 configurations 对象里面添加一个新的配置项
“configurations": {
.....
"hmr": {
"fileReplacements": [{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.hmr.ts"
}]
}
}然后找到 serve 对象配置一下 [xxxxx修改成自己的项目名称即可]
"serve": {
"builder": "@angular-devkit/build-angular:dev-server", "options": {
"browserTarget": "xxxxx:build"
}, "configurations": {
"production": {
"browserTarget": "xxxxx:build:production"
},
"hmr": {
"browserTarget": "xxxxx:build:hmr",
"hmr": true
}
}
}},5. 最后在 package.json 文件添加启动命令,然后 npm run hmr 即可
"hmr": "ng serve -c=hmr --disable-host-check"