Matt RaibleMatt Raible is a Web Architecture Consultant specializing in open source frameworks.

10+ YEARS


Over 10 years ago, I wrote my first blog post. Since then, I've authored books, had kids, traveled the world, found Trish and blogged about it all.

Using Grunt with AngularJS for Front End Optimization

I'm passionate about front end optimization and have been for years. My original inspiration was Steve Souders and his Even Faster Web Sites talk at OSCON 2008. Since then, I've optimized this blog, made it even faster with a new design, doubled the speed of several apps for clients and showed how to make AppFuse faster. As part of my Devoxx 2013 presentation, I showed how to do page speed optimization in a Java webapp.

I developed a couple AngularJS apps last year. To concat and minify their stylesheets and scripts, I used mechanisms that already existed in the projects. On one project, it was Ant and its concat task. On the other, it was part of a Grails application, so I used the resources and yui-minify-resources plugins.

The Angular project I'm working on now will be published on a web server, as well as bundled in an iOS native app. Therefore, I turned to Grunt to do the optimization this time. I found it to be quite simple, once I figured out how to make it work with Angular. Based on my findings, I submitted a pull request to add Grunt to angular-seed.

Below are the steps I used to add Grunt to my Angular project.

  1. Install Grunt's command line interface with "sudo npm install -g grunt-cli".
  2. Edit package.json to include a version number (e.g. "version": "1.0.0").
  3. Add Grunt plugins in package.json to do concat/minify/asset versioning:
        "grunt": "~0.4.1",
        "grunt-contrib-concat": "~0.3.0",
        "grunt-contrib-uglify": "~0.2.7",
        "grunt-contrib-cssmin": "~0.7.0",
        "grunt-usemin": "~2.0.2",
        "grunt-contrib-copy": "~0.5.0",
        "grunt-rev": "~0.1.0",
        "grunt-contrib-clean": "~0.5.0"
    
  4. Run "sudo npm install" to install the project's dependencies.
  5. Create a Gruntfile.js that runs all the plugins.
    module.exports = function (grunt) {
    
        grunt.initConfig({
            pkg: grunt.file.readJSON('package.json'),
    
            clean: ["dist", '.tmp'],
    
            copy: {
                main: {
                    expand: true,
                    cwd: 'app/',
                    src: ['**', '!js/**', '!lib/**', '!**/*.css'],
                    dest: 'dist/'
                },
                shims: {
                    expand: true,
                    cwd: 'app/lib/webshim/shims',
                    src: ['**'],
                    dest: 'dist/js/shims'
                }
            },
    
            rev: {
                files: {
                    src: ['dist/**/*.{js,css}', '!dist/js/shims/**']
                }
            },
    
            useminPrepare: {
                html: 'app/index.html'
            },
    
            usemin: {
                html: ['dist/index.html']
            },
    
            uglify: {
                options: {
                    report: 'min',
                    mangle: false
                }
            }
        });
    
        grunt.loadNpmTasks('grunt-contrib-clean');
        grunt.loadNpmTasks('grunt-contrib-copy');
        grunt.loadNpmTasks('grunt-contrib-concat');
        grunt.loadNpmTasks('grunt-contrib-cssmin');
        grunt.loadNpmTasks('grunt-contrib-uglify');
        grunt.loadNpmTasks('grunt-rev');
        grunt.loadNpmTasks('grunt-usemin');
    
        // Tell Grunt what to do when we type "grunt" into the terminal
        grunt.registerTask('default', [
            'copy', 'useminPrepare', 'concat', 'uglify', 'cssmin', 'rev', 'usemin'
        ]);
    };
    
  6. Add comments to app/index.html so usemin knows what files to process. The comments are the important part, your files will likely be different.
    <!-- build:css css/app-name.min.css -->
    <link rel="stylesheet" href="lib/bootstrap/bootstrap.min.css"/>
    <link rel="stylesheet" href="lib/font-awesome/font-awesome.min.css"/>
    <link rel="stylesheet" href="lib/toaster/toaster.css"/>
    <link rel="stylesheet" href="css/app.css"/>
    <link rel="stylesheet" href="css/custom.css"/>
    <link rel="stylesheet" href="css/responsive.css"/>
    <!-- endbuild -->
    ...
    
    <!-- build:js js/app-name.min.js -->
    <script src="lib/jquery/jquery-1.10.2.min.js"></script>
    <script src="lib/bootstrap/bootstrap.min.js"></script>
    <script src="lib/angular/angular.min.js"></script>
    <script src="lib/angular/angular-animate.min.js"></script>
    <script src="lib/angular/angular-cookies.min.js"></script>
    <script src="lib/angular/angular-resource.min.js"></script>
    <script src="lib/angular/angular-route.min.js"></script>
    <script src="lib/fastclick.min.js"></script>
    <script src="lib/toaster/toaster.js"></script>
    <script src="lib/webshim/modernizr.min.js"></script>
    <script src="lib/webshim/polyfiller.min.js"></script>
    <script src="js/app.js"></script>
    <script src="js/services.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/filters.js"></script>
    <script src="js/directives.js"></script>
    <!-- endbuild -->
    

A couple of things to note: 1) the copy task copies the "shims" directory from Webshims lib because it loads files dynamically and 2) setting "mangle: false" on the uglify task is necessary for Angular's dependency injection to work. I tried to use grunt-ngmin with uglify and had no luck.

After making these changes, I'm able to run "grunt" and get an optimized version of my app in the "dist" folder of my project. For development, I continue to run the app from my "app" folder, so I don't currently have a need for watching and processing assets on-the-fly. That could change if I start using LESS or CoffeeScript.

The results speak for themselves: from 27 requests to 5 on initial load, and only 3 requests for less than 2K after that.

YSlow Page Speed
No optimization 75
27 HTTP requests / 464K
55/100
Apache optimization (gzip and expires headers) 89
initial load: 26 requests / 166K
primed cache: 4 requests / 40K
88/100
Apache + concat/minified/versioned files 98
initial load: 5 requests / 136K
primed cache: 3 requests / 1.4K
93/100

Update: Andreas Andreou has a nice tip on how to reduce the LOC in this example.

  1. Add "matchdep" as a dependency in package.json (or run "sudo npm install matchdep --save-dev").
    "matchdep": "~0.3.0"
    
  2. Replace all the grunt.loadNpmTasks(...) calls with the following:
    require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
    

Thanks Andreas!

Posted in The Web at Jan 15 2014, 12:15:52 PM MST 3 Comments
Comments:

[Trackback] After writing yesterday's article on optimizing AngularJS apps with Grunt I received an interesting reply from @markj9 on Twitter. @mraible that might be a bad thing! you should go listen to Igor..&#10; http://t.co/HL2mho7R86 &mdash; Mark ...

Posted by Raible Designs on January 16, 2014 at 03:06 PM MST #

I dont see any code to specify the dependency while concatenating angularjs files.

Posted by Rajaguru Duraisamy on August 17, 2014 at 01:41 PM MDT #

grunt-contrib-concat does the concatenation and uglify does the minifying.

Posted by Matt Raible on August 18, 2014 at 10:31 AM MDT #

Post a Comment:
  • HTML Syntax: Allowed