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

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.

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 front-end 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/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 Web Application and name the new project “MovieAngularJSApp”.

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 is divided into two solution folders named Solution Items and src. The src folder contains all of the source code for your project. Currently, the src folder includes our MovieAngularJSApp project.

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

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

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

Using NPM to Get the Necessary Packages

Unlike 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 to create 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 their dependencies 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 your project with the project.json file.

ASP.NET 5 also supports NPM packages. This is new and exciting. The NPM package manager was originally created for managing packages for the open-source NodeJS framework (an alternative web app framework to ASP.NET). You use a file 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 is designed to support front-end development. You can use Bower to manage resources such as AngularJS, jQuery, and Bootstrap.

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 to install 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. Modify the file so that it looks like this:


1

2

3

4

5

6

7

8

9

{

    "version": "0.0.0",

    "name": "MovieAngularJSApp",

    "devDependencies": {

        "grunt": "0.4.5",

        "grunt-contrib-uglify": "0.7.0",

        "grunt-contrib-watch": "0.6.1"

    }

}

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 NPM package 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 you expand the NPM folder then you can see a list of all of the NPM packages that you just added to the package.json file.

Right-click the NPM folder and select Restore Packages to download all of the NPM packages. After you complete this step, 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. For example, 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 from the Google CDN instead. I am going to add AngularJS to my project Index.html page like this:


1

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

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 need to download the AngularJS JavaScript library when you visit each website. The browser can retrieve AngularJS from its cache instead.

So I use a CDN for standard libraries such as AngularJS or jQuery that might be used with multiple websites. For app specific 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 Files

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

In this blog post, I’ll show you how to use Grunt to combine and minify your JavaScript files. We’ll configure Grunt so that it will take all of the JavaScript files from the Scripts folder, combine and minify the files, and save the results to a file named 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 the Gruntfile.js file so that it looks like this:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

module.exports = function (grunt) {

    // load Grunt plugins from NPM

    grunt.loadNpmTasks(‘grunt-contrib-uglify‘);

    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‘]);

};

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

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


1

2

3

4

5

uglify: {

   my_target: {

      files: { ‘wwwroot/app.js‘: [‘Scripts/app.js‘, ‘Scripts/**/*.js‘] }

   }

},

Notice that I use the array [‘Scripts/app.js’, ‘Scripts/**/*.js’] to specify the source files. I want the contents of the app.js JavaScript file to appear in the combined JavaScript file before the contents of any other JavaScript files because the app.js file contains the declaration of my main AngularJS module. In other words, if you want to control the order in which 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:


1

2

3

4

5

6

watch: {

   scripts: {

      files: [‘Scripts/**/*.js‘],

      tasks: [‘uglify‘]

   }

}

If any files in the Scripts folder are changed, then the Watch plugin reruns Uglify to generate a new combined and minified 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” task that 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 MovieAngularJSApp appears.
  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 the Scripts folder. Whenever you modify any JavaScript file in the Scripts folder then a new app.js file is generated in the wwwroot folder automatically.

Summary

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

http://stephenwalther.com/archive/2015/01/12/asp-net-5-and-angularjs-part-1-configuring-grunt-uglify-and-angularjs

时间: 2024-08-24 22:26:41

ASP.NET 5 and AngularJS Part 1, Configuring Grunt, Uglify, and AngularJS的相关文章

[后端人员耍前端系列]AngularJs篇:30分钟快速掌握AngularJs

一.前言 对于前端系列,自然少不了AngularJs的介绍了.在前面文章中,我们介绍了如何使用KnockoutJs来打造一个单页面程序,后面一篇文章将介绍如何使用AngularJs的开发一个单页面应用程序.在开始使用AngularJs开发SPA之前,我觉得有必要详细介绍下AngularJs所涉及的知识点.所有也就有了这篇文章. 二.AngularJs介绍 AngularJS是Google推出的一款Web应用开发框架.它提供了一系列兼容性良好并可扩展的服务,包括数据绑定.DOM操作.MVC和依赖注

AngularJS(三)——在多个AngularJS controller之间共享数据

在MVC中,为了方便维护,针对不同业务会使用不同的controller.有时我们需要在不同的controller中共享数据,本文旨在解决这一问题. 1. 使用$rootScope直接绑定 AngularJS中有一个$rootScope对象,它是AngularJS中最接近全局作用域的对象,是所有$scope对象的最上层,可以简单理解为BOM中的window对象或Node.js中的global对象.最简单的方式是直接将要共享的数据绑定到$rootScope对象中: <!DOCTYPE html>

angularjs ocLazyLoad分步加载js文件,angularjs ocLazyLoad按需加载js

用angular有一段时间了,平日里只顾着写代码,没有注意到性能优化的问题,而今有时间,于是捋了捋,讲学习过程记录于此: 问题描述:由于采用angular做了网页的单页面应用,需要一次性在主布局中将所有模块需要引用到的js都引入.对于比较小的项目,这是可行的,但是对于大的项目,一旦js文件较多,在页面首次加载时就引入所有js文件,无疑会延缓页面加载的速度,造成不良额用户体验.那么分布加载(按需加载)就显得很有必要了. <!DOCTYPE html> <html lang="en

[AngularJS] Write a simple Redux store in AngularJS app

The first things we need to do is create a reducer: /** * CONSTANT * @type {string} */ export const GET_CATEGORIES = "GET_CATEGORIES"; /** * INIT VALUE */ export const initialCategories = [ {id: 0, name: 'Development'}, {id: 1, name: 'Design'},

[译]用AngularJS构建大型ASP.NET单页应用(二)

原文地址:http://www.codeproject.com/Articles/808213/Developing-a-Large-Scale-Application-with-a-Single 客户管理页面-新增.修改客户 单页应用中的页面与asp.net页面类似,两者都是html页面. 对于asp.net,浏览器加载html.js.数据,然后,浏览器进展示.而单页应用,页面内容通过ng-view 指令被注入到一个div标签中. 页面初始化时,浏览器通常只渲染html代码. 若在单页应用中使

购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(1)--后端

原文:购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(1)--后端 chsakell分享了前端使用AngularJS,后端使用ASP.NET Web API的购物车案例,非常精彩,这里这里记录下对此项目的理解. 文章:http://chsakell.com/2015/01/31/angularjs-feat-web-api/http://chsakell.com/2015/03/07/angularjs-feat-web-api-enable-session-

使用ASP.NET 5开发AngularJS应用

今天推荐的是一个系列文章,讲述了如何使用ASP.NET 5来开发AngularJS应用,一共7篇文章. 在Visual Studio 2015中由于优化了项目结构,优化了前端JS框架的引用方式,所以开发AngularJS这样的应用就更加方便了. 这个讲述如何使用ASP.NET 5来开发AngularJS应用的系列文章,一共分为7篇,分别介绍了: 配置Grunt.Uglify和AngularJS.大致步骤为.1)如何创建在一个空的Web应用项目中.2)利用NPM来安装Grunt执行器及其任务(gr

AngularJS 简易入门

AngularJS 简介 AngularJS 是一个 JavaScript 框架.它可通过 <script> 标签添加到 HTML 页面. AngularJS 通过 指令 扩展了 HTML,且通过 表达式 绑定数据到 HTML. AngularJS 是以一个 JavaScript 文件形式发布的,可通过 script 标签添加到网页中 注意:建议把脚本放在 <body> 元素的底部.这会提高网页加载速度,因为 HTML 加载不受制于脚本加载. AngularJS 扩展了 HTML

使用 AngularJS 开发一个大规模的单页应用(SPA)

本文的目标是基于单页面应用程序开发出拥有数百页的内容,包括认证,授权,会话状态等功能,可以支持上千个用户的企业级应用. 下载源代码 介绍 (SPA)这样一个名字里面蕴含着什么呢? 如果你是经典的Seinfeld电视秀的粉丝,那么你一定知道Donna Chang这个名字.Jerry跟Donna见面,Donna其实不是华人,但是却因在谈论其对中国的固有印象比如在针灸上的兴趣,以及偶然的一次单词发音带上了点儿中文口音,她将自己末尾的名字缩成了Chang Donna 在电话上同George的母亲交谈,(