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 , , , , , , , 77 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.

77 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
    Replies
    1. IEEE Final Year projects Project Center in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes. Final Year Project Domains for IT

      JavaScript Training in Chennai

      JavaScript Training in Chennai

      The Angular Training covers a wide range of topics including Components, project projects for cse. Angular Training

      Delete

  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. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic.


    Pawn Shop

    Pawn Loans

    Pawn Shops

    Pawn Loan

    Pawn Shop near me

    ReplyDelete
  4. 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
  5. this is great posti like the way you explain little things thanks for sharing
    tutuapp apk
    instagram sign up

    ReplyDelete
  6. I ‘d mention that most of us visitors are endowed to exist in a fabulous place with very many wonderful individuals with very helpful things.
    fire and safety course in chennai

    ReplyDelete

  7. 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

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

    ReplyDelete
  9. 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
  10. For Big Data And Hadoop Training in Bangalore Visit - Big Data And Hadoop Training In Bangalore

    ReplyDelete
  11. 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
  12. This comment has been removed by the author.

    ReplyDelete
  13. 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
  14. Wow! Such an amazing and helpful post this is. I really really love it. I hope that you continue to do your work like this in the future also.
    Ethical Hacking Training in Bangalore
    Ethical Hacking Training

    ReplyDelete
  15. 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
  16. Very informative blog and useful article thank you for sharing with us,
    by cloudi5 offers AWS Training in Chennai

    ReplyDelete
  17. 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

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

    ReplyDelete
  19. 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
  20. All of pitbull dog and puppy are sent home. Current on shots, deworming, flea treated, health certificate, genetic health guarantee, and AKC registration papers. All new families are required to sign a contract that includes a basic health guarantee and a 3 year genetic health guarantee.
    Pitbull Puppies For Sale
    american pitbull terrier puppies
    pitbull puppies for sale near me
    pitbull breeders for sale
    pit bull breeders near me
    pit bull puppy
    baby pitbulls for sale

    ReplyDelete
  21. All of pitbull dog and puppy are sent home. Current on shots, deworming, flea treated, health certificate, genetic health guarantee, and AKC registration papers. All new families are required to sign a contract that includes a basic health guarantee and a 3 year genetic health guarantee.
    Pitbull Puppies For Sale
    american pitbull terrier puppies
    pitbull puppies for sale near me
    pitbull breeders for sale
    pit bull breeders near me
    pit bull puppy
    baby pitbulls for sale

    ReplyDelete
  22. The Pomsky is a designer breed of dog that is a hybrid of the Pomeranian and the Siberian Husky. Adorable Pomsky puppies have attracted a lot of attention recently and made them one of the most popular breeds of 2017.
    Best Online Pet Adoption : Cavapoo Puppies For Sale : Australian Shepherd Puppies Below $200 : Available Maltipoo Puppies Online : Where To Buy Golden Retriever Puppies OnlineBest Online Adoption|Healthy Puppies for Sale|Cavapoo puppies for sale

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

    ReplyDelete
  24. i am glad to discover this page : i have to thank you for the time i spent on this especially great reading !! i really liked each part and also bookmarked you for new information on your site.
    data scientist course in bangalore

    ReplyDelete
  25. Thanks for Sharing a Very Informative Post & I read Your Article & I must say that is very helpful post for us.
    Data Science Course in Pune
    Python Classes in Pune

    ReplyDelete
  26. Nice blog, very informative content.Thanks for sharing, waiting for the next update…
    Data Science Tutorial
    data science for beginners

    ReplyDelete
  27. valuable blog,Informative content...thanks for sharing, Waiting for the next update…
    Google Flutter and Dart Online Training
    Flutter Online Courses

    ReplyDelete
  28. Nice article, its very informative content..thanks for sharing...Waiting for the next update.

    Ionic Online Course
    Ionic Online Training

    ReplyDelete
  29. Post is really impressive... Thanks for the data update and waiting for your new updates.
    Android Training in Chennai
    Android Online Training
    Android Training in Coimbatore

    ReplyDelete
  30. 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
  31. Mobilemall Bangladesh Really nice blog. thanks for sharing such a useful information.

    ReplyDelete


  32. marijuana has been a stepping stone to the medical condition of most patients.
    many people suffering from cancer, chronic pain, anxiety, and many more have overcome their aillments with cannabis.
    you can order weed from our store.medical condition

    ReplyDelete

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

    ReplyDelete
  34. Most valuable and fantastic blog I really appreciate your work which you have done about the electricians,many thanks and keep it up. Very useful info. Hope to see more posts soon! I really like to read this post, it shares lots of information to readers.a

    Graphic Design company in USA

    Label Design

    Box Packaging Design

    Packaging Host

    Die Cut Stickers

    Static Cling

    Lahore Smart City Payment Plan

    Hosting Mart

    Lahore Smart City

    ReplyDelete
  35. 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
  36. You actually make it look so easy with your performance but I find this matter to be actually something which I think I would never comprehend. It seems too complicated and extremely broad for me. I'm looking forward for your next post, I’ll try to get the hang of it! data science course in mysore

    ReplyDelete
  37. I was just examining through the web looking for certain information and ran over your blog.It shows how well you understand this subject. Bookmarked this page, will return for extra.https://360digitmg.com/course/project-management-professional-pmp

    ReplyDelete
  38. 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
  39. This comment has been removed by the author.

    ReplyDelete