如题:angular nrwl/nx项目 hmr 热更新设置
nx介绍:https://nx.dev/getting-started/what-is-nx
设置:
1、angular.json设置:
// 对应 app 的build与serve下的configurations加 hmr, 同时设置environments目录相应ts
"build": {
"configurations": {
"hmr": {
"fileReplacements": [
{
"replace": "apps/system-admin/src/environments/environment.ts",
"with": "apps/system-admin/src/environments/environment.hmr.ts"
}
]
}
},
}
"serve": {
"configurations": {
"production": {
"browserTarget": "midback-admin:build:production"
},
"hmr": {
"hmr": true,
"browserTarget": "midback-admin:build:hmr"
}
}
}
app相应设置,先上个目录结构,以下标红箭头是需要配置的文件:
// environment 目录3个文件
//environment.hmr.ts
export const environment = {
production: false,
hmr: true,
};
//environment.prod.ts
export const environment = {
production: true,
hmr: false,
};
//environment.ts
export const environment = {
production: false,
hmr: false,
};
hmr.ts
import { NgModuleRef, ApplicationRef } from '@angular/core';
import { createNewHosts } from '@angularclass/hmr';
export const hmrBootstrap = (
module: any,
bootstrap: () => Promise>,
) => {
let ngModule: NgModuleRef;
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();
});
};
main.ts
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));
}
启动程序:yarn ng serve --configuration hmr --project my-app
如果报错:main.ts error TS2304: Cannot find name 'module'. 那就在 tsconfig.app.json 加配置:"types": ["node"]
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc/apps/vendor-admin",
"types": ["node"]
},
"exclude": [
"test.ts",
"**/*.spec.ts"
],
"include": [
"**/*.ts"
, "../../libs/vendor-admin/views/vendor-admin/src/index.ts"
]
}
重新启动app,这时应该就没有问题了,试一下修改代码,保存,页面就不会刷新了,一下子人都精神了!!!
如有遗漏,后面补充!