Using the Ahead-of-Time (AOT) Compiler | Pluralsight
文章推薦指數: 80 %
The Ahead-of-Time (AOT) Compiler ... We can decrease the size of the build and compile it at the time of the build. This means the application can ... GauravSinghalUsingtheAhead-of-Time(AOT)CompilerGauravSinghalJan23,20208Minread2,706ViewsJan23,20208Minread2,706ViewsLanguagesFrameworksandToolsAngularIntroduction17IntroductionWhatisaCompiler ?TheCompilerinAngularTheAhead-of-Time(AOT)CompilerHowAOTWorksCodeAnalysisCodeGenerationTemplateTypeCheckingConclusionTopIntroductionInthisguide,we'regoingtolearnabouttheahead-of-timecompiler,alsoknownasAOT.ThisisanimportanttopicthatwillimpacttheperformanceofyourAngularapplication.WhatisaCompiler ?Acompilerisnothingbutachunkofcodethatconvertsaprogramminglanguagetoanotherprogramminglanguage.IfwetalkaboutClanguage,whichisaverybasicprogramminglanguage,thecompilerneedstoconverttheprogramfromCtobytecodetoexecute.Machinesdon'tknowlanguageslikeCorJava.Theyonlyunderstandthelanguageofbytes.That'swhyweneedtoconvertcodefromonelanguagetoanotherlanguage.Browsers,however,don'tunderstandbytecode.TheyunderstandthelanguagesofHTML,CSS,andJavaScript. Theydon'tunderstandhigh-levellanguageslikeSASS,SCSS,orjQuery.TheselanguagesneedtobeconvertedintoHTML,CSSorJavaScript.TheCompilerinAngularAnAngularapplicationconsistsofcomponentsandtheirtemplates,providedbyAngulartoenhanceproductivitysoyoucanmakeanappmorequicklywithhighperformance.Browsersdon'tknowthelanguageoftemplatesandcomponents.AsIsaidbefore,theyonlyknowthelanguagesofHTML,CSS,andJavaScript.SoweneedtoconvertfromatemplatetoaJavaScriptprogram. Weneedacompiler.Angularhastwotypesofcompilers.:Just-in-Time(JIT)Ahead-of-Time(AOT)Just-in-TimeCompilerThejust-in-timecompilerdoesthecompilationprocessatthetimeofrendering.Youcanhosttheprogramatthelocalhostwiththefollowingcommand :1ngserveconsoleIfyouhavetohostitsomewherelikeAWS,thenyouneedtomakeabuildofit.Youcanmakeabuildwiththefollowingcommand :1ngbuild--prodconsole--prodallowstheapplicationtotaketheconfigurationoftheproductionlevelthathasbeenconfiguredintheAngularapp. AngularchecksthesyntaxoftheAngularprogramandaddstheangularcompiler,whichcantranslateaprogramfromcomponenttoactualJavaScript.Theangularcompilerbuildgetsheavy,andittakesmoretimetodownloadtheprograminthebrowser.Afterdownload,Angularcompilestheprogram,whichalsotakessometimetotranslatefromcomponenttoJavaScript.Thisaffectsinrenderingtimeoftheapplicationinthebrowser.TheAhead-of-Time(AOT)CompilerWecandecreasethesizeofthebuildandcompileitatthetimeofthebuild.Thismeanstheapplicationcanbequicklydownloadedbythebrowseranddoesn'tneedtospendthetimetocompiletheprogram.Thisispossiblewiththeahead-of-time(AOT)compiler.AOTcompilestheprogramatthebuildinglevelsothebrowserdoesn'tneedtospendthetimetocompileit.Theprogramisalreadycompiled,andAngulardoesn'taddcompilerintothebuild.Thishelpstodecreasethesizeofthebuild.Youdon'thavetodomuchfortheAOTcompiler—justhavesomeextraparametersincommandoftheJITcompiler.Ifyouhavetohostinlocal,hitthefollowingcommand:1ngserve--aotconsoleIfyouhavetomakeabuildtohostitsomewherelikeAWS,hitthefollowingcommand:1ngbuild--prod--aotconsoleHowAOTWorksTheAngularAOTcompilerextractsthemetadatatointerprettheAngularapplicationinequivalentJavaScriptcode.Itrecognizesthecodebasedondecoratorslike@Component,@Input,@Output,@ViewChild,etc.1import{Component}from'@angular/core'; 2 3@Component({ 4selector:'app-root', 5templateUrl:'./app.component.html', 6styleUrls:['./app.component.scss'], 7}) 8exportclassAppComponent{ 9title='Appcomponent'; 10@Input()testInput; 11}tsAsyoucansee,intheaboveexamplewehavetwodecorators:@Componentand@Input.TheAngularcompilertreatsbothdecoratorsdifferentlyandgeneratesafactoryforcomponents.Whenitneedstocreatetheinstanceofthecomponent,itcallsthefactory,whichproducesanewelement.TheAngularAOTCompilercompilesitin3phases :CodeanalysisCodegenerationTemplatetypecheckingCodeAnalysisTheTypescriptcompilerdoessomeoftheanalyticsworkinthefirstphase.Afteranalytics,itemitsthefilewiththeextensionof.d.tsthatAOTCompilerneedstogeneratetheapplicationcode.Atthesametime,AOTCollectorcollectsthemetadataandanalyzesitthatrecordedinAngulardecoratorslike@Component,@NgModule,@Directive.Oncetheanalyzingprocessisdone,itemitsthemetadatainformationin.metadata.jsonfiles.TheAOTcompileronlyunderstandsasubsetofJavaScript.Itdoesn'tknowthewholeJavaScriptsyntax.Supposeyouwanttomakeyourownproviderforaservice,andyouwanttowritetheprogramasbelow.1@Component({ 2... 3providers:[{provide:server,useFactory:()=>newServer()}] 4})tsInthisexample,theprovidekeywordacceptsanInjectiontokenthatshouldbeuniqueanduseFactoryacceptsafunctionthatreturnsaninstanceofaservice.Thereisnoerrorwiththeprogram,buttheAOTcompilerdoesn'tknowthelambdaexpressionanditthrowsanerror.ButsinceAngularversion5,itconvertstheprogramasbelow :1exportfunctionserverFactory(){ 2returnnewServer(); 3} 4 5@Component({ 6... 7providers:[{provide:server,useFactory:serverFactory}] 8})tsTheAngularcompileralsodoesn'tsupportthefunctionorkeywordthat'snotbeingexported. Intheprogramabove,youcanseewehavethesamefunctionthatreturninganinstanceofserverandfunctionisgettingexported.TheAOTcompilersupportsmostsyntaxfromJavaScriptbutnotall.Thesearesomeofthesyntaxes:Literalobject({key1:value1,key2:value2})LiteralArray([item1,item2,item3])NullConditionaloperator(expression?value1:value2)CodeGenerationThecodecollectoronlycollectsthecodeandgivestheoutputin.metadata.json.Itdoesn'tinterprettheJavaScriptcode.Inthesecondphase,thisjobgetsdone. Thecompilerdoesthejobofcodegenerationandthrowsanerrorifthereareanysemanticerrors.SomeoftheerrorsIwouldliketomentionarepublicerrors.ThevariableusedintheHTMLtemplateshouldbepublicintheTSfile.Supposewe'veused@Inputforadatabindinginthetsfile,soitshouldbepublic.1{{title}}html1import{Component}from'@angular/core'; 2 3@Component({ 4selector:'app-root', 5templateUrl:'./app.component.html', 6styleUrls:['./app.component.scss'], 7}) 8exportclassAppComponent{ 9title='Appcomponent'; 10}tsAsyoucanseeinabovecode,I'veusedthetitlevariabletodisplayitintheHTMLfile.Ikeptakeywordaspublic.Ididn'tmentionthepublickeywordbecauseTypescriptissetaspublicifnoaccessspecifierismentioned.TemplateTypeCheckingAftercodegeneration,thecompilerchecksoutthetemplatetype.Itchecksthevariableandfunctioninthetypescriptfilethatyou'veusedintheHTMLtemplatetodisplayortoapplythecondition.SupposeyouhaveusedanisEvent(n)functionintheHTMLtemplatetocheckwhetherthenumberisevenorodd.TheAOTcompilerchecksitintypescript,andifitdoesn'tpresent,thenitthrowsanerrorlikeisEventisnotafunction.1import{Component}from'@angular/core'; 2 3@Component({ 4selector:'app-root', 5template:'Evennumber', 6styleUrls:['./app.component.scss'], 7}) 8exportclassAppComponent{ 9title='Appcomponent'; 10}tsIntheaboveprogram,I'veusedthefunctionisEvenbuthaven'tmentioneditintypescript.SotheAOTcompilerwillthrowtheerror.Afterthesethreephases,theAOTcompilercompletesitsjobandmakesabuildifeverythingiswritten,otherwiseitthrowstheerror.AlthoughtheAngularAOTcompilercheckedalltheconditionsandinterpretedthematthetimeofbuild,itdoesn'taddthecompilerintothebuild,whichhelpstomakethebuildsmaller.ConclusionThanksforreadingthisarticle.IhopeithashelpedyoutounderstandtheAOTconceptmoreclearly.Youcanreadmoreaboutithere.17LEARNMORE
延伸文章資訊
- 1AOT - Mono Project
Ahead of Time Compilation or AOT is a feature of the Mono runtime code generator. The Mono code g...
- 2Just-in-Time (JIT) and Ahead-of-Time (AOT) Compilation in ...
An ahead-of-time (AOT) compiler converts your code during the build time before the browser downl...
- 3[Day 25] Angular 2 事先編譯Ahead-of-Time (AoT) - iT 邦幫忙
... 本身是即時編譯(Just-in-Time, JiT),瀏覽器先讀取我們的檔案,然後瀏覽器邊看邊編譯,但這樣比起有先編譯過當然慢了多,如果事先編譯(Ahead-of-Time, AoT) ...
- 4Angular 4 教學- Webpack 預先編譯Ahead-of-Time (AOT)
Ahead-of-Time (AOT) 預先編譯,是在程式發佈之前就透過Angular Compiler 進行編譯,所以瀏覽器下載完的 *.js 檔案,就可以直接被執行,然後渲染畫面 ...
- 5Ahead of Time Compilation (AoT) | Baeldung
AOT compilation is one way of improving the performance of Java programs and in particular the st...