My studying notebook

2014/07/02

AngularJs, RequireJs, Grunt and Bower Part2 - Grunt (Update: 2014/7/15)

7/02/2014 11:29:00 AM Posted by Kai-Chu Chung , , , , , , , 3 comments

This article is part of a series of posts on RequireJs, AnguarJs, Grunt and Bower. Here are the parts so far:

  1. AngularJs, RequireJs, Grunt and Bower Part1 - Getting Started and concept with ASP.NET MVC
  2. AngularJs, RequireJs, Grunt and Bower Part2 - Grunt
  3. AngularJs, RequireJs, Grunt and Bower Part3 - generator-angular-requirejs-grunt-bower with ASP.NET MVC
  4. AngularJs, RequireJs, Grunt and Bower Part4 - How to extend your own code with ASP.NET MVC
  5. AngularJs, RequireJs, Grunt and Bower Part5 - generator-angular-requirejs-grunt-bower with Express.js //to be done

Grunt

Grunt

Why use a task runner?

In one word: automation. The less work you have to do when performing repetitive tasks like minification, compilation, unit testing, linting, etc, the easier your job becomes. After you’ve configured it, a task runner can do most of that mundane work for you—and your team—with basically zero effort.

Why use Grunt?

The Grunt ecosystem is huge and it’s growing every day. With literally hundreds of plugins to choose from, you can use Grunt to automate just about anything with a minimum of effort. If someone hasn’t already built what you need, authoring and publishing your own Grunt plugin to npm is a breeze.

If you are familiar with Grunt. You could feel how powerful it is, how could it reduce your repetitive tasks and make your work more easier.

Grunt with our ASP.NET MVC Project

Concept

...
Public
    └── js
    |   ├── controllers
    |   ├── css
    |   ├── directives
    |   ├── services
    |   ├── vendor
    |   ├── filters
    |   ├── views
    |   |   └── ...
    |   ├── app.js
    |   └── config.js
    └── release
        ├── views
        |   └── ...
        ├── app.js
        └── config.js       

RequireJs, AnguarJs, Grunt, Bower overview

In AngularJs, RequireJs, Grunt and Bower Part1 - Getting Started and concept with ASP.NET MVC ~ 竹部落 post. We talk about how to integrate AngularJs, RequireJs, Grunt and Bower with our ASP.NET MVC project and put all of code in Public/js folder. Browser will load those files one by one by following RequireJs definition and dependencies we define in Public/js/config.js.

Be a large AngularJs single page application, you might include a lots of file to the project. For example: in our ASP.NET MVC project. Implement the file structure i mentioned in last post. Browser will load more the 20 file. Web page loading speed will increase if browser load more files. During development, separation of concerns (SoC) will help us to break down the problem to smaller. So, we need a solution to help us to combine related file and decrease web page loding speed in release mode. That’s Rquirejs + Grunt.

RequireJs + Grunt

Our gold is improve page loading speed by reduce include file count in our project in final release/product. RequireJs has an optimization tool can help us to combine related file and minifies them and grunt-contrib-requirejs and put RequireJs work with Grunt well.

REQUIREJS OPTIMIZER

Combines related scripts together into build layers and minifies them via UglifyJS (the default) or Closure Compiler (an option when using Java).
Optimizes CSS by inlining CSS files referenced by @import and removing comments.

Gruntfile.js
module.exports = function(grunt) {
    'use strict';
    require('load-grunt-tasks')(grunt);

    // configurable paths
    var mvcConfig = {
        js: 'js',
        release: 'release',
        tmp: 'tmp'
    };

    grunt.initConfig({
        mvc: mvcConfig,
        clean: {...},
        copy: {...},
        requirejs: {...},
        concat: {...},
        uglify: {...},
        htmlmin: {...},
        jshint: {...},
        cssmin: {...}
    });

    // task
    grunt.registerTask('build', [
        'clean:release',
        'clean:tmp',
        'copy:vendor',
        'copy:module',
        'requirejs',
        'copy:basic',
        'copy:css',
        'cssmin',
        'clean:tmp',
        'htmlmin'
    ]);

    grunt.registerTask('default', [
        'jshint',
        'build'
    ]);
};

Grunt scenario

We can define multiple grunt tasks in Gruntfile.js. All you need to do is executing command grunt. Grunt will execute all of tasks one by one. How, let we check before doing the grunt task.

  • using bower package manager to handle what library we include and put all libraries in vendor. Ex: AngularJs, jQuery , moment ects.
  • config.js define the library dependencies and library path.
  • implement file structure as we mentioned before.

Our Grunt scenario is copy required file from public/js/... to public/tmp/... folder. Grunt task requirejs:complie will combine scripts together and put it in public/release folder.

grunt-contrib-requirejs optimize RequireJS projects using r.js. Most of needed configuration is same as RequireJs required but file path. We need to modify file path to our temporary folder tmp.

 paths: {
        ...
        'angular': '../<%= mvc.tmp %>/vendor/angular',
        'jquery': '../<%= mvc.tmp %>/vendor/jquery.min',
        ...

One more thing. We need to replace file path in our release RequireJs config.js from js to release. It will make sure relese RequireJs config.js is reference to current source folder.

onBuildRead: function(moduleName, path, contents) {
    if (moduleName === 'config') {
        var x = (function(contents) {
            var regex = /'(vendor|libs)[^']*'/gm;
            var matches = contents.match(regex);
            for (var i = 0; i < matches.length; i++) {
                var match = matches[i];
                var m = matches[i].split('/');
                contents = contents.replace(match, '\'vendor/' + m[m.length - 1].toLowerCase());
            }
            return contents;
        })(contents);

        return x.replace(/\/public\/js/g, '/public/release');
    }
    return contents;
},

Visit to Github to check whole Gruntfile.js file.

build.txt

After you execute command grunt. build.txt will be created automatically. It is a requirejs:complie log file and show you a list what libraries and user define scripts are combined together base on Gruntfile.js requirejs complie module setting.

// config.js
requirejs: {
    compile: {
        options: {
            ...
            modules: [{
                name: 'views/Home/index'
            }],
            ...
        }
    }
},
// build.txt
views/Home/index.js
----------------
vendor/jquery.min.js
vendor/moment.min.js
vendor/angular.js
vendor/respond.js
controllers/controllers.js
filters/filters.js
directives/directives.js
vendor/angular-resource.js
services/services.js
vendor/angular-animate.js
vendor/angular-cookies.js
vendor/angular-route.js
vendor/angular-sanitize.js
vendor/angular-touch.js
vendor/bootstrap.min.js
vendor/ui-bootstrap.min.js
vendor/ui-bootstrap-tpls.min.js
app.js
vendor/domReady.js
controllers/home-controller.js
views/Home/index.js

Preview

Final step, we need to change solution configuration from Debug to Release in Visual Studio toolbar and rebuild the project. Open Chrome Developer tools and switch to Network panel. You will see browser load two files config.js and index.js

Release mode

Reference

  1. Grunt: The JavaScript Task Runner
  2. RequireJs

Github Source Code

cage1016/AngularJsRequireJsGruntBower

After you clone source code from github repo, you can run following command:

  • git checkout -f step-0 is status project created
  • git checkout -f step-1 is status Nuget install Require.js.
  • git checkout -f step-2 is status project Add AngularJs, RequireJs, Grunt and Bower to Public folder.
  • git checkout -f step-3 is status modify _Layout.chtml to render RequireJs. You will see the final result.
    • Please cd to AngularJsRequireJsGruntBower\AngularJsRequireJsGruntBower\Public and execute bower install to restore those library project included.
  • git checkout -f setp-4 is status ready to do grunt tasks.
    • Please cd to AngularJsRequireJsGruntBower\AngularJsRequireJsGruntBower\Public and execute npm install to restore grunt required libraries.
    • execute command grunt to do grunt tasks.

3 comments:

  1. Pretty post, I hope your site useful for many users who want to learn basics of programming to enhance their skill for getting good career in IT, thanks for taking time to discuss about fundamental programming niche.
    With Regards,
    Angularjs training in chennai|Angularjs course in chennai

    ReplyDelete

  2. The oracle database is capable of storing the data in two forms such as logically in the form of table spaces and physically like data files.
    Oracle Training in Chennai | oracle dba training in chennai

    ReplyDelete