Você está na página 1de 12

January12th,2015

ASP.NET5andAngularJSPart1,ConfiguringGrunt,Uglify,andAngularJS
ThisisthefirstpartinamultiplepartblogseriesonbuildingASP.NET5(ASP.NETvNext)appswithAngularJS.Inthis
seriesofblogposts,IshowhowyoucancreateasimpleMovieappusingASP.NET5,MVC6,andAngularJS.
ASP.NET5andAngularJSPart1,Grunt,Uglify,andAngularJS
ASP.NET5andAngularJSPart2,UsingtheMVC6WebAPI
ASP.NET5andAngularJSPart3,AddingClientRouting
ASP.NET5andAngularJSPart4,UsingEntityFramework7
ASP.NET5andAngularJSPart5,FormValidation
ASP.NET5andAngularJSPart6,Security
ASP.NET5andAngularJSPart7,RunningonaMac
YoucandownloadthecodediscussedinthisblogpostfromGitHub:
https://github.com/StephenWalther/MovieAngularJSApp
Inthisblogpost,IexplainhowtosetupyourASP.NET5project.Inparticular,IexplainhowyoucansetupGruntto
combineandminifyyourfrontendJavaScriptfilesautomatically.

CreatingtheASP.NET5Project
TheveryfirstthingthatyouneedtodoistocreateanewASP.NET5project.Inthisblogpost,Illshowyouhowtocreate
anewASP.NET5projectusingVisualStudio2015onWindows(Inafutureblogpost,Illdiscusshowyoucansetupan
ASP.NET5projectonaMaconOSXwithSublime).
YoucandownloadVisualStudio2015(Preview)fromthefollowingaddress:
IfyoulikedthisblogentrythenpleaseSubscribetoMy
BlogorFollowMeonTwitter
http://www.visualstudio.com/enus/downloads/visualstudio2015downloadsvs.aspx
VisualStudio2015worksfinerunningsidebysidewithearlierversionsofVisualStudio.
AfteryouinstallVisualStudio2015,selectFile,NewProject.UndertheVisualC#templates,selectASP.NETWeb
ApplicationandnamethenewprojectMovieAngularJSApp.

Next,selecttheASP.NET5EmptyprojecttemplateandclicktheOKbuttontocreatethenewproject.

Afteryoucompletethesesteps,youllhaveanemptyASP.NET5projectthatlookslikethis:

ThelayoutofanASP.NET5solutionissignificantlydifferentthanearlierversionsofASP.NET.Noticethatthesolutionis
dividedintotwosolutionfoldersnamedSolutionItemsandsrc.Thesrcfoldercontainsallofthesourcecodeforyour
project.Currently,thesrcfolderincludesourMovieAngularJSAppproject.
TheMovieAngularJSAppprojectcontainsaspecialfoldernamedwwwroot.Theideahereisthatthewwwrootfolder
shouldcontainallofthecontentofyourlivewebsite.Forexample,itincludesanyHTMLfilesandimageassetsrequired
foryourlivewebsite.
Youshouldnotplaceanyofyoursourcecodeinthewwwrootfolder.Instead,sourcecodesuchasunminified
JavaScriptfiles,Lessfiles,MVCcontrollersourcecode,andC#modelclassesshouldbeplacedoutsideofthewwwroot
folder.
Inparticular,youwanttocreateafolderintherootofyourMovieAngularJSAppprojectnamedScripts.Youllcreateallof
yourappsJavaScriptfilesintheScriptsfolder.WelluseGrunttocombineandminifytheJavaScriptfilesintheScripts
folderandaddtheresulttothewwwrootfolderautomatically.

UsingNPMtoGettheNecessaryPackages
UnlikeearlierversionsofASP.NET,ASP.NET5nativelysupportsthreepackagemanagers:NuGet,NPM,andBower.
Whatisapackagemanager?Apackagemanagerenablesyoutoeasilygathertogetheralloftheresourcesthatyouneedto
createaproject.Forexample,insteadofnavigatingaroundthewebanddownloadingprojectresourcessuchasjQuery,
theEntityFramework,Bootstrap,andAngularJSbyhand,youcandownloadalloftheseresourcesandtheir
dependenciesautomaticallybytakingadvantageofapackagemanager.
PreviousversionsofASP.NETsupportedNuGetandyoullstilluseNuGetwithASP.NET5.YoulluseNuGettomanage
.NETpackagessuchasASP.NETMVCandtheEntityFramework.YouspecifytheNuGetpackagesthatyouneedinyour
projectwiththeproject.jsonfile.
ASP.NET5alsosupportsNPMpackages.Thisisnewandexciting.TheNPMpackagemanagerwasoriginallycreatedfor
managingpackagesfortheopensourceNodeJSframework(analternativewebappframeworktoASP.NET).Youusea
filenamedpackage.jsontomanageyourprojectsNPMpackages.
Finally,ASP.NET5alsosupportstheBowerpackagemanager.BowerisapackagemanagercreatedbyTwitterthatis
designedtosupportfrontenddevelopment.YoucanuseBowertomanageresourcessuchasAngularJS,jQuery,and
Bootstrap.
ForourMovieappproject,weneedtouseNPMtogatheralloftheresourcesthatweneedtouseGrunt.WelluseNPMto
installGruntandtheGruntpluginsthatweneed.Followthesesteps:
1. RightclickyourMovieAngularJSAppprojectandselectthemenuoptionAdd,NewItem.

2. SelectNPMconfigurationfile.
3. ClicktheAddbutton.

CompletingthesestepswilladdanewfiletotherootofyourMovieAngularJSAppprojectnamedpackage.json.Modify
thefilesothatitlookslikethis:

1
2
3
4
5
6
7
8
9

{
"version":"0.0.0",
"name":"MovieAngularJSApp",
"devDependencies":{
"grunt":"0.4.5",
"gruntcontribuglify":"0.7.0",
"gruntcontribwatch":"0.6.1"
}
}

Inourpackage.jsonfile,weveindicatedthatweneedthreeNPMpackagesnamedgrunt,gruntcontribuglify,andgrunt
contribwatch.Afterthenameofeachpackage,wevespecifiedtheversionofthepackagethatweneed.
NoticethatyougetIntellisense(autocomplete)supportwhileyoueditthepackage.jsonfile.AmatchinglistofNPM
packagenamesandversionnumbersappearasyoutype.
Afteryoucreatethepackage.jsonfile,anewfoldernamedNPMappearsunderyourprojectsDependenciesfolder.Ifyou
expandtheNPMfolderthenyoucanseealistofalloftheNPMpackagesthatyoujustaddedtothepackage.jsonfile.

RightclicktheNPMfolderandselectRestorePackagestodownloadalloftheNPMpackages.Afteryoucompletethis
step,thegrunt,gruntcontribuglify,andgruntcontribwatchpackageswillallbeinstalledtoafoldernamednode
modules.

WhataboutBower?
YoucanuseBower,asImentionedearlier,tomanageallofthepackagesthatyouneedforfrontenddevelopment.For
example,youcanuseBowertoinstalltheAngularJSJavaScriptlibrary.
ImnotgoingtouseBowertoinstallAngularJSinthisprojectbecauseIamgoingtoreferenceAngularJSdirectlyfrom
theGoogleCDNinstead.IamgoingtoaddAngularJStomyprojectIndex.htmlpagelikethis:

<scriptsrc="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>

Thisiscontroversial,butIbelievethatyoushouldalwaysuseaCDNforstandardlibrariessuchasAngularJS,Bootstrap,
andjQuery.UsingaCDNprovidesyouwiththebestperformance.
Forexample,ifyouvisitmultiplewebsitesthatallreferenceAngularJSfromthesameCDNthenyourbrowserdoesnot

needtodownloadtheAngularJSJavaScriptlibrarywhenyouvisiteachwebsite.ThebrowsercanretrieveAngularJSfrom
itscacheinstead.
SoIuseaCDNforstandardlibrariessuchasAngularJSorjQuerythatmightbeusedwithmultiplewebsites.Forapp
specificfiles,suchastheAngularJScontrollerfiles,IuseGrunttocombineandminifythefilestoimproveperformance.

UsingGrunttoBuildYourJavaScriptFiles
Gruntisanopensourcetoolthatyoucanusetobuildallofthefrontendresourcesforyourproject.Forexample,youcan
useGrunttocompileyourLessorSassfilesintoCSS.YoucanalsouseGrunttocombineandminifyCSSandJavaScript
files.
Inthisblogpost,IllshowyouhowtouseGrunttocombineandminifyyourJavaScriptfiles.WellconfigureGruntso
thatitwilltakealloftheJavaScriptfilesfromtheScriptsfolder,combineandminifythefiles,andsavetheresultstoafile
namedapp.jsinthewwwrootfolder.
Followthesesteps:
1. RightclickyourMovieAngularJSAppprojectandselectAdd,NewItem.
2. SelectGruntConfigurationfile.
3. ClicktheAddbutton.

Afteryoucompletethesesteps,yourprojectwillcontainanewfilenamedGruntfile.js.Modifythecontentsofthe
Gruntfile.jsfilesothatitlookslikethis:

1
2
3

module.exports=function(grunt){
//loadGruntpluginsfromNPM
grunt.loadNpmTasks('gruntcontribuglify');

4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

grunt.loadNpmTasks('gruntcontribwatch');

//configureplugins
grunt.initConfig({
uglify:{
my_target:{
files:{'wwwroot/app.js':['Scripts/app.js','Scripts/**/*.js']}
}
},

watch:{
scripts:{
files:['Scripts/**/*.js'],
tasks:['uglify']
}
}
});

//definetasks
grunt.registerTask('default',['uglify','watch']);
};

OurGruntfilecontainsthreesections.ThefirstsectionisusedtoloadeachoftheGruntpluginsthatweneedfromthe
NPMpackagesthatweconfiguredearlier.WeneedtouseaGruntpluginnamedgruntcontribuglifyandaGruntplugin
namedgruntcontribwatch.
Next,weentertheconfigurationinformationforeachplugin.TheUglifypluginisconfiguredsothatitcombinesand
minifiesallofthefilesfromtheScriptsfolderandplacestheresultsinafilenamedapp.jsinthewwwrootfolder:

1
2
3
4
5

uglify:{
my_target:{
files:{'wwwroot/app.js':['Scripts/app.js','Scripts/**/*.js']}
}
},

NoticethatIusethearray[Scripts/app.js,Scripts/**/*.js]tospecifythesourcefiles.Iwantthecontentsoftheapp.js
JavaScriptfiletoappearinthecombinedJavaScriptfilebeforethecontentsofanyotherJavaScriptfilesbecausethe
app.jsfilecontainsthedeclarationofmymainAngularJSmodule.Inotherwords,ifyouwanttocontroltheorderin
whichUglifycombinesJavaScriptfilesthenyouneedtolisttheorderofyourJavaScriptfilesexplicitly.
TheWatchpluginisconfiguredtowatchanychangestotheJavaScriptfilesintheScriptsfolderwiththefollowingcode:

1
2
3
4
5
6

watch:{
scripts:{
files:['Scripts/**/*.js'],
tasks:['uglify']
}
}

IfanyfilesintheScriptsfolderarechanged,thentheWatchpluginrerunsUglifytogenerateanewcombinedand
minifiedapp.jsfileautomatically.
ThefinalsectionoftheGruntfilecontainsadefinitionsforyourtasks.InourGruntfile,wedefineasingledefaulttask
thatrunsUglifyandthenwatchesforchangesinourJavaScriptfiles.
AfteryoucreateaGruntfile,youneedtorunitbyusingtheVisualStudioTaskRunnerExplorer.Followthesesteps:
1. SelectthemenuoptionView,OtherWindows,TaskRunnerExplorer.
2. ClicktheRefreshbuttonintheTaskRunnerExplorerwindowtoensurethatthetasksfortheMovieAngularJSApp
appears.

3. RightclicktheDefaulttaskandselectRun.

Afteryoucompletethesesteps,youcanverifythatGruntisworkingbyaddingaJavaScriptfile(anyJavaScriptfile)tothe
Scriptsfolder.WheneveryoumodifyanyJavaScriptfileintheScriptsfolderthenanewapp.jsfileisgeneratedinthe
wwwrootfolderautomatically.

Summary
Inthisblogpost,IfocusedonsettingupanewASP.NET5andAngularJSproject.IconfiguredNPMandGruntsothat
myappspecificJavaScriptfileswillbecombinedandminifiedautomatically.Inthenextblogpost,Illexplainhowyou
cancreateAngularJStemplatesthatdisplaymoviesretrievedfromMVC6WebAPI.

ASP.NET5/MVC6Training
LearnMVC6fromStephenWalther.Weflytoyou!
LearnMore

Discussion
mohammad January12,2015at8:08pm

Hi
itsverynicetohearaboutyourupcomingstoresonmvc5,itsbeenalittlelongsinceanyseriesonmvc5serieserred
made.Ihopeyouwilladdasectionwhereuserscanloginandupdatedata.

Mohammad January13,2015at7:52am

HiStephen!
ItsverynicetohearthatyouhaveplannedtomakeaserieonASP.NETMVC5.Ibelieveitsbeenalittlelongsinceany
seriesonMVC5weremadebyanyone.Ihopeyouwillexpandtheseriebyhavingapartwhereuserscanloginand
updatedata.
Sincerely
Mohammad

grahamesd January15,2015at2:14pm

WithallthechangesinVSvnextandASP.NETvnext,especiallythesolutionstructure,itsgreattohaveawalkthrough
likethis.Thanks!

StephenO January16,2015at7:42am

IthinkyouonlyusedanangularCDNbecauseyouknewhowtediousitistoopulltheminthroughapackagemangeror
copythemtoyourwwwroot!
Anychanceyoucouldshowusthebestwaytomanagevendorscripts?andpossiblyhowwecouldseparatetheAPIintoa
separateproject?

Categories
ACT(19)

AJAX(73)

ApplicationBuilding(28)

ASP.NET(155)

ASP.NETMVC(128)

ASP.NETMVCFramework
Unleashed(18)

ASP.NETUnleashed(3)

Books(14)

CDN(4)

JavaScript(45)

jQuery(22)

Meteor(3)

Metro(17)

Scrum(2)

SonicAgile(2)

Talks(23)

TDD(25)

Tips(52)

Uncategorized(3)

Windows8Apps(4)

WindowsAzure(2)

Recentarticles
Top10ChangesinASP.NET5andMVC6
UpdateonApril,302015WhenIwrotethisblogpost,IwrotethatMicrosoftwasnotplanningtosupportVB.NETin
ASP.NET5/MVC6.ThatwastruewhenIwrotetheblogpost,butthisblogpostgeneratedsomestrongreactionsfromthe
VB.NETcommunity.Well,itlookslikeVB.NETisback!http://www.infoq.com/news/2015/04/VBCoreI[]
ASP.NET5DeepDive:Routing
Inthisblogpost,IfocusonhowroutingisimplementedinASP.NET5andMVC6.Iexplainhowtocreateroutes,use
RESTfulroutes,anduserouteconstraints.Whileresearchingthisblogpost,Itookfulladvantageoftheopensourcecode
forASP.NET5locatedatthefollowingGitHubrepositories:https://github.com/aspnetRoutingin[]
ASP.NET5andAngularJSPart7,RunningonaMac
ThisistheseventhpartinamultiplepartblogseriesonbuildingASP.NET5(ASP.NETvNext)appswithAngularJS.In
thisseriesofblogposts,IshowhowyoucancreateasimpleMovieappusingASP.NET5,MVC6,andAngularJS.
ASP.NET5andAngularJSPart1,Grunt,Uglify,andAngularJSASP.NET5[]
ASP.NET5andAngularJSPart6,Security
ThisisthesixthpartinamultiplepartblogseriesonbuildingASP.NET5(ASP.NETvNext)appswithAngularJS.Inthis
seriesofblogposts,IshowhowyoucancreateasimpleMovieappusingASP.NET5,MVC6,andAngularJS.ASP.NET5
andAngularJSPart1,Grunt,Uglify,andAngularJSASP.NET5[]
ASP.NET5andAngularJSPart5,FormValidation
ThisisthefifthpartinamultiplepartblogseriesonbuildingASP.NET5(ASP.NETvNext)appswithAngularJS.Inthis
seriesofblogposts,IshowhowyoucancreateasimpleMovieappusingASP.NET5,MVC6,andAngularJS.ASP.NET5
andAngularJSPart1,Grunt,Uglify,andAngularJSASP.NET5[]

COPYRIGHT2015STEPHENWALTHER

Você também pode gostar