Angular hmr 적용하기

hmr 이란?

Hot Module Replacement의 약자로 모듈의 변경사항을 실시간으로 어플리케이션에 반영한다.

angular에 environment 추가하기

environment.hmr.ts 파일 만들기

1
2
3
4
export const environment = {
production: false,
hmr: true
};

src/environments/environment.prod.ts 수정하기

1
2
3
4
export const environment = {
production: true,
hmr: false
};

src/environments/environment.ts 수정하기

1
2
3
4
export const environment = {
production: false,
hmr: false
};

angular-cli.json 수정하기

1
2
3
4
5
6
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"hmr": "environments/environment.hmr.ts",
"prod": "environments/environment.prod.ts"
},

package.json 수정하기

1
2
3
4
5
6
7
8
"scripts": {
"start": "ng serve",
"hmr": "ng serve --hmr -e=hmr",
"lint": "tslint \"src/**/*.ts\"",
"test": "ng test",
"pree2e": "webdriver-manager update",
"e2e": "protractor"
}

npm run hmr 명령어를 통해 environment를 적용할 수 있다.

hmr 모듈 import 하기

1
npm install --save-dev @angularclass/hmr

src/hmr.ts 생성하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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 수정하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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();
}

새로운 환경 반영하기

1
npm run hmr

출처


머신러닝강의 01. 머신러닝의 기본 개념 마케팅 강의 01. 마케팅의 기본 개념

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×