JIT和AOT編譯介紹
JIT - Just-In-Time 實時編譯,即時編譯
通常所說的JIT的優勢是Profile-Based Optimization,也就是邊跑邊優化,根據運行時信息然后隨着時間的推移得到盡可能最優的代碼,適用於開發調試。
AOT - Ahead-Of-Time 預先編譯,靜態編譯
AOT與JIT對比有以下優點:
在客戶端我們不需要導入體積龐大的angular編譯器,這樣可以減少我們 JS 腳本庫的大小。使用 AOT 編譯后的應用,不再包含任何 HTML 片段,取而代之的是編譯生成的 TypeScript 代碼,這樣的話 TypeScript 編譯器就能提前發現錯誤。總而言之,采用 AOT 編譯模式,我們的模板是類型安全的。適用於部署發布。
特性 JIT AOT
編譯平台 (Browser) 瀏覽器 (Server) 服務器
編譯時機 Runtime (運行時) Build (構建階段)
包大小 較大 較小
執行性能 慢 更好
啟動時間 長 更短
Angular JIT和AOT編譯
基於JIT(Just in Time)編譯器的動態引導
在main.ts使用JIT模式
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
基於AOT(Ahead of Time)編譯器的靜態引導
在main.ts使用AOT模式
import { platformBrowser } from '@angular/platform-browser';
import { AppModuleNgFactory } from './app.module.ngfactory';
platformBrowser().bootstrapModuleFactory(AppModuleNgFactory);
JIT和AOT編譯器都會生產AppModuleNgFactory,只是方式不一樣。JIT在瀏覽器,緩存里實時生產AppModuleNgFactory 。AOT編譯器會生產一個物理文件app.module.ngfactory。AOT模式引入這個文件,然后啟動:
import { AppModuleNgFactory } from './app.module.ngfactory';
生成app.module.ngfactory
@angular/compiler-cli提供了tsc和AOT兩種編譯器,把TypeScript轉換為Javascript:
安裝ngc
npm install @angular/compiler-cli typescript@next @angular/platform-server @angular/compiler