Using the Ahead-of-Time (AOT) Compiler | Pluralsight

文章推薦指數: 80 %
投票人數:10人

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



請為這篇文章評分?