Part1_Grunt Uglify and AngularJS

12
January 12th, 2015 ASP.NET 5 and AngularJS Part 1, Configuring Grunt, Uglify, and AngularJS This is the first part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS. ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJS ASP.NET 5 and AngularJS Part 2, Using the MVC 6 Web API ASP.NET 5 and AngularJS Part 3, Adding Client Routing ASP.NET 5 and AngularJS Part 4, Using Entity Framework 7 ASP.NET 5 and AngularJS Part 5, Form Validation ASP.NET 5 and AngularJS Part 6, Security ASP.NET 5 and AngularJS Part 7, Running on a Mac You can download the code discussed in this blog post from GitHub: https://github.com/StephenWalther/MovieAngularJSApp In this blog post, I explain how to setup your ASP.NET 5 project. In particular, I explain how you can setup Grunt to combine and minify your frontend JavaScript files automatically. Creating the ASP.NET 5 Project The very first thing that you need to do is to create a new ASP.NET 5 project. In this blog post, I’ll show you how to create a new ASP.NET 5 project using Visual Studio 2015 on Windows (In a future blog post, I’ll discuss how you can setup an ASP.NET 5 project on a Mac on OSX with Sublime). You can download Visual Studio 2015 (Preview) from the following address: http://www.visualstudio.com/enus/downloads/visualstudio2015downloadsvs.aspx Visual Studio 2015 works fine running sidebyside with earlier versions of Visual Studio. After you install Visual Studio 2015, select File, New Project. Under the Visual C# templates, select ASP.NET Web Application and name the new project “MovieAngularJSApp”. If you liked this blog entry then please Subscribe to My Blog or Follow Me on Twitter

description

Grunt Uglify and AngularJS

Transcript of Part1_Grunt Uglify and AngularJS

January 12th, 2015

ASP.NET 5 and AngularJS Part 1, Configuring Grunt, Uglify, and AngularJS

This is the first part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In thisseries of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS.

ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJSASP.NET 5 and AngularJS Part 2, Using the MVC 6 Web APIASP.NET 5 and AngularJS Part 3, Adding Client RoutingASP.NET 5 and AngularJS Part 4, Using Entity Framework 7ASP.NET 5 and AngularJS Part 5, Form ValidationASP.NET 5 and AngularJS Part 6, SecurityASP.NET 5 and AngularJS Part 7, Running on a Mac

You can download the code discussed in this blog post from GitHub:

https://github.com/StephenWalther/MovieAngularJSApp

In this blog post, I explain how to setup your ASP.NET 5 project. In particular, I explain how you can setup Grunt tocombine and minify your front­end JavaScript files automatically.

Creating the ASP.NET 5 ProjectThe very first thing that you need to do is to create a new ASP.NET 5 project. In this blog post, I’ll show you how to createa new ASP.NET 5 project using Visual Studio 2015 on Windows (In a future blog post, I’ll discuss how you can setup anASP.NET 5 project on a Mac on OSX with Sublime).

You can download Visual Studio 2015 (Preview) from the following address:

http://www.visualstudio.com/en­us/downloads/visual­studio­2015­downloads­vs.aspx

Visual Studio 2015 works fine running side­by­side with earlier versions of Visual Studio.

After you install Visual Studio 2015, select File, New Project. Under the Visual C# templates, select ASP.NET WebApplication and name the new project “MovieAngularJSApp”.

If you liked this blog entry then please Subscribe to MyBlog or Follow Me on Twitter

Next, select the ASP.NET 5 Empty project template and click the OK button to create the new project.

After you complete these steps, you’ll have an empty ASP.NET 5 project that looks like this:

The layout of an ASP.NET 5 solution is significantly different than earlier versions of ASP.NET. Notice that the solution isdivided into two solution folders named Solution Items and src. The src folder contains all of the source code for yourproject. Currently, the src folder includes our MovieAngularJSApp project.

The MovieAngularJSApp project contains a special folder named wwwroot. The idea here is that the wwwroot foldershould contain all of the content of your live website. For example, it includes any HTML files and image assets requiredfor your live website.

You should not place any of your source code in the wwwroot folder. Instead, source code — such as unminifiedJavaScript files, Less files, MVC controller source code, and C# model classes – should be placed outside of the wwwrootfolder.

In particular, you want to create a folder in the root of your MovieAngularJSApp project named Scripts. You’ll create all ofyour app’s JavaScript files in the Scripts folder. We’ll use Grunt to combine and minify the JavaScript files in the Scriptsfolder and add the result to the wwwroot folder automatically.

Using NPM to Get the Necessary PackagesUnlike earlier versions of ASP.NET, ASP.NET 5 natively supports three package managers: NuGet, NPM, and Bower.

What is a package manager? A package manager enables you to easily gather together all of the resources that you need tocreate a project. For example, instead of navigating around the web and downloading project resources such as jQuery,the Entity Framework, Bootstrap, and AngularJS by hand, you can download all of these resources and theirdependencies automatically by taking advantage of a package manager.

Previous versions of ASP.NET supported NuGet and you’ll still use NuGet with ASP.NET 5. You’ll use NuGet to manage.NET packages such as ASP.NET MVC and the Entity Framework. You specify the NuGet packages that you need in yourproject with the project.json file.

ASP.NET 5 also supports NPM packages. This is new and exciting. The NPM package manager was originally created formanaging packages for the open­source NodeJS framework (an alternative web app framework to ASP.NET). You use afile named package.json to manage your project’s NPM packages.

Finally, ASP.NET 5 also supports the Bower package manager. Bower is a package manager created by Twitter that isdesigned to support front­end development. You can use Bower to manage resources such as AngularJS, jQuery, andBootstrap.

For our Movie app project, we need to use NPM to gather all of the resources that we need to use Grunt. We’ll use NPM toinstall Grunt and the Grunt plugins that we need. Follow these steps:

1.  Right­click your MovieAngularJSApp project and select the menu option Add, New Item.

2.  Select NPM configuration file.

3.  Click the Add button.

Completing these steps will add a new file to the root of your MovieAngularJSApp project named package.json. Modifythe file so that it looks like this:

In our package.json file, we’ve indicated that we need three NPM packages named grunt, grunt­contrib­uglify, and grunt­contrib­watch. After the name of each package, we’ve specified the version of the package that we need.

Notice that you get Intellisense (autocomplete) support while you edit the package.json file. A matching list of NPMpackage names and version numbers appear as you type.

After you create the package.json file, a new folder named NPM appears under your project’s Dependencies folder. If youexpand the NPM folder then you can see a list of all of the NPM packages that you just added to the package.json file.

123456789

{    "version": "0.0.0",    "name": "MovieAngularJSApp",    "devDependencies": {        "grunt": "0.4.5",        "grunt‐contrib‐uglify": "0.7.0",        "grunt‐contrib‐watch": "0.6.1"    }}

Right­click the NPM folder and select Restore Packages to download all of the NPM packages. After you complete thisstep, the grunt, grunt­contrib­uglify, and grunt­contrib­watch packages will all be installed to a folder named node­modules.

What about Bower?You can use Bower, as I mentioned earlier, to manage all of the packages that you need for front­end development. Forexample, you can use Bower to install the AngularJS JavaScript library.

I’m not going to use Bower to install AngularJS in this project because I am going to reference AngularJS directly fromthe Google CDN instead. I am going to add AngularJS to my project Index.html page like this:

This is controversial, but I believe that you should always use a CDN for standard libraries such as AngularJS, Bootstrap,and jQuery. Using a CDN provides you with the best performance.

For example, if you visit multiple websites that all reference AngularJS from the same CDN then your browser does not

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

need to download the AngularJS JavaScript library when you visit each website. The browser can retrieve AngularJS fromits cache instead.

So I use a CDN for standard libraries such as AngularJS or jQuery that might be used with multiple websites. For appspecific files, such as the AngularJS controller files, I use Grunt to combine and minify the files to improve performance.

Using Grunt to Build Your JavaScript FilesGrunt is an open­source tool that you can use to build all of the frontend resources for your project. For example, you canuse Grunt to compile your Less or Sass files into CSS. You can also use Grunt to combine and minify CSS and JavaScriptfiles.

In this blog post, I’ll show you how to use Grunt to combine and minify your JavaScript files. We’ll configure Grunt sothat it will take all of the JavaScript files from the Scripts folder, combine and minify the files, and save the results to a filenamed app.js in the wwwroot folder.

Follow these steps:

1.  Right­click your MovieAngularJSApp project and select Add, New Item.

2.  Select Grunt Configuration file.

3.  Click the Add button.

After you complete these steps, your project will contain a new file named Gruntfile.js. Modify the contents of theGruntfile.js file so that it looks like this:

123

module.exports = function (grunt) {    // load Grunt plugins from NPM    grunt.loadNpmTasks('grunt‐contrib‐uglify');

Our Gruntfile contains three sections. The first section is used to load each of the Grunt plugins that we need from theNPM packages that we configured earlier. We need to use a Grunt plugin named grunt­contrib­uglify and a Grunt pluginnamed grunt­contrib­watch.

Next, we enter the configuration information for each plugin. The Uglify plugin is configured so that it combines andminifies all of the files from the Scripts folder and places the results in a file named app.js in the wwwroot folder:

Notice that I use the array [‘Scripts/app.js’, ‘Scripts/**/*.js’] to specify the source files. I want the contents of the app.jsJavaScript file to appear in the combined JavaScript file before the contents of any other JavaScript files because theapp.js file contains the declaration of my main AngularJS module. In other words, if you want to control the order inwhich Uglify combines JavaScript files then you need to list the order of your JavaScript files explicitly.

The Watch plugin is configured to watch any changes to the JavaScript files in the Scripts folder with the following code:

If any files in the Scripts folder are changed, then the Watch plugin reruns Uglify to generate a new combined andminified app.js file automatically.

The final section of the Grunt file contains a definitions for your tasks. In our Grunt file, we define a single “default” taskthat runs Uglify and then watches for changes in our JavaScript files.

After you create a Grunt file, you need to run it by using the Visual Studio Task Runner Explorer. Follow these steps:

1.  Select the menu option View, Other Windows, Task Runner Explorer.

2.  Click the Refresh button in the Task Runner Explorer window to ensure that the tasks for the MovieAngularJSAppappears.

456789101112131415161718192021222324

    grunt.loadNpmTasks('grunt‐contrib‐watch');     // configure plugins    grunt.initConfig({        uglify: {            my_target: {                files: { 'wwwroot/app.js': ['Scripts/app.js', 'Scripts/**/*.js'] }            }        },         watch: {            scripts: {                files: ['Scripts/**/*.js'],                tasks: ['uglify']            }        }    });     // define tasks    grunt.registerTask('default', ['uglify', 'watch']);}; 

12345

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

123456

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

3.  Right­click the Default task and select Run.

After you complete these steps, you can verify that Grunt is working by adding a JavaScript file (any JavaScript file) to theScripts folder. Whenever you modify any JavaScript file in the Scripts folder then a new app.js file is generated in thewwwroot folder automatically.

SummaryIn this blog post, I focused on setting up a new ASP.NET 5 and AngularJS project. I configured NPM and Grunt so thatmy app specific JavaScript files will be combined and minified automatically. In the next blog post, I’ll explain how youcan create AngularJS templates that display movies retrieved from MVC 6 Web API.

ASP.NET 5/MVC 6 TrainingLearn MVC 6 from Stephen Walther. We fly to you! Learn More

Discussion

mohammad January 12, 2015 at 8:08 pm

Hiit’s very nice to hear about your upcoming stores on mvc 5, it’s been a little long since any series on mvc 5 series erredmade. I hope you will add a section where users can login and update data.

Mohammad January 13, 2015 at 7:52 am

Hi Stephen!It’s very nice to hear that you have planned to make a serie on ASP.NET MVC 5. I believe it’s been a little long since anyseries on MVC 5 were made by anyone. I hope you will expand the serie by having a part where users can login andupdate data.SincerelyMohammad

grahamesd January 15, 2015 at 2:14 pm

ACT (19) AJAX (73) Application Building (28) ASP.NET (155)

ASP.NET MVC (128) ASP.NET MVC FrameworkUnleashed (18)

ASP.NET Unleashed (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) Windows 8 Apps (4) Windows Azure (2)

Categories

Recent articles

Top 10 Changes in ASP.NET 5 and MVC 6Update on April, 30 2015 When I wrote this blog post, I wrote that Microsoft was not planning to support VB.NET inASP.NET 5/MVC 6. That was true when I wrote the blog post, but this blog post generated some strong reactions from theVB.NET community. Well, it looks like VB.NET is back! http://www.infoq.com/news/2015/04/VB­Core I […]

ASP.NET 5 Deep Dive: RoutingIn this blog post, I focus on how routing is implemented in ASP.NET 5 and MVC 6. I explain how to create routes, useRESTful routes, and use route constraints. While researching this blog post, I took full advantage of the open­source codefor ASP.NET 5 located at the following GitHub repositories: https://github.com/aspnet Routing in […]

ASP.NET 5 and AngularJS Part 7, Running on a MacThis is the seventh part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. Inthis series of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS.ASP.NET 5 and AngularJS Part 1, Grunt, Uglify, and AngularJS ASP.NET 5 […]

ASP.NET 5 and AngularJS Part 6, SecurityThis is the sixth part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In thisseries of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS. ASP.NET 5and AngularJS Part 1, Grunt, Uglify, and AngularJS ASP.NET 5 […]

ASP.NET 5 and AngularJS Part 5, Form ValidationThis is the fifth part in a multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In thisseries of blog posts, I show how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS. ASP.NET 5and AngularJS Part 1, Grunt, Uglify, and AngularJS ASP.NET 5 […]

With all the changes in VS vnext and ASP.NET vnext, especially the solution structure, it’s great to have a walkthroughlike this. Thanks!

Stephen O January 16, 2015 at 7:42 am

I think you only used an angular CDN because you knew how tedious it is too pull them in through a package manger orcopy them to your wwwroot! 

Any chance you could show us the best way to manage vendor scripts? and possibly how we could separate the APIinto aseparate project?

COPYRIGHT © 2015 STEPHEN WALTHER