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 Unknown , , , , , , , 51 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.

51 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
  3. My rather long internet look up has at the end of the day been compensated with pleasant insight to talk about with my family and friends.
    big-data-hadoop-training-institute-in-bangalore

    ReplyDelete
  4. this is great posti like the way you explain little things thanks for sharing
    tutuapp apk
    instagram sign up

    ReplyDelete

  5. I enjoyed over read your blog post. Your blog have nice information, I got good ideas from this amazing blog. I am always searching like this type blog post. I hope I will see again.
    site...


    ReplyDelete

  6. Thanks for sharing the information. It is very useful for my future. keep sharing
    site...

    ReplyDelete
  7. Thank you for allowing me to read it, welcome to the next in a recent article. And thanks for sharing the nice article, keep posting or updating news article.
    mobile service centre

    ReplyDelete
  8. For Big Data And Hadoop Training in Bangalore Visit - Big Data And Hadoop Training In Bangalore

    ReplyDelete
  9. Hey Nice Blog!! Thanks For Sharing!!! Wonderful blog & good post. It is really very helpful to me, waiting for a more new post. Keep Blogging!Here is the best angular training online with free Bundle videos .

    contact No :- 9885022027.

    SVR Technologies

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. Thanks for the informative article About Java. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.

    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  12. I just recently discovered your blog and have now scrolled through the entire thing several times. I am very impressed and inspired by your skill and creativity, and your "style" is very much in line with mine. I hope you keep blogging and sharing your design idea

    java training in chennai

    java training in velachery

    aws training in chennai

    aws training in velachery

    python training in chennai

    python training in velachery

    selenium training in chennai

    selenium training in velachery

    ReplyDelete
  13. Very informative blog and useful article thank you for sharing with us,
    by cloudi5 offers AWS Training in Chennai

    ReplyDelete
  14. Honestly speaking this blog is absolutely amazing in learning the subject that is building up the knowledge of every individual and enlarging to develop the skills which can be applied in to practical one. Finally, thanking the blogger to launch more further too.

    Data Science Course in Bhilai

    ReplyDelete

  15. Way cool! Some very valid points! I appreciate you penning this article and also the rest of the site is really good.
    Technology

    ReplyDelete
  16. I think this is an informative post and it is very useful and knowledgeable. therefore. I would like to thank you for the efforts you have made in writing this article.
    DevOps Training in Chennai

    DevOps Course in Chennai

    ReplyDelete
  17. Cognex offers AWS training in Chennai using classroom and AWS Online Training globally.
    click here

    ReplyDelete
  18. This is a very nice one and gives in-depth information. I am really happy with the quality and presentation of the article. I’d really like to appreciate the efforts you get with writing this post. Thanks for sharing.

    Python classes in Ahmednagar
    Python classes in Amravati
    Python classes in Nashik

    ReplyDelete
  19. Mobilemall Bangladesh Really nice blog. thanks for sharing such a useful information.

    ReplyDelete

  20. This post is so interactive and informative.keep update more information...
    Tally Course in Tambaram
    Tally course in Chennai

    ReplyDelete
  21. Very Informative, good stuff. A good article is one that a person is aware of, to get something to learn from that article and your article is also one of them.We hope that you will share a similar article in the future and make us aware thank you.

    Read more articles here:

    The Masters Real Estate

    Lahore Smart City

    Capital Smart City map

    Faisalabad Smart City

    Park View City Islamabad

    Park View City Lahore

    Nova City Islamabad

    ReplyDelete
  22. 360DigiTMG, the top-rated organisation among the most prestigious industries around the world, is an educational destination for those looking to pursue their dreams around the globe. The company is changing careers of many people through constant improvement, 360DigiTMG provides an outstanding learning experience and distinguishes itself from the pack. 360DigiTMG is a prominent global presence by offering world-class training. Its main office is in India and subsidiaries across Malaysia, USA, East Asia, Australia, Uk, Netherlands, and the Middle East.

    ReplyDelete
  23. This comment has been removed by the author.

    ReplyDelete
  24. thanks for sharing valuable info..........

    SSR Movies

    ReplyDelete
  25. Thanks for sharing important information about Angular requirejs , keep posting , also wanted to learn about Python then visit: Python Training in Pune
    python programming classes in Pune

    ReplyDelete