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.
- Install Grunt's command line interface with "sudo npm install -g grunt-cli".
- Edit package.json to include a version number (e.g. "version": "1.0.0").
- 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"
- Run "sudo npm install" to install the project's dependencies.
- 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' ]); };
- 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.
- Add "matchdep" as a dependency in package.json (or run "sudo npm install matchdep --save-dev").
"matchdep": "~0.3.0"
- Replace all the
grunt.loadNpmTasks(...)
calls with the following:require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
Thanks Andreas!
Posted by Raible Designs on January 16, 2014 at 09:06 PM MST #
Posted by Rajaguru Duraisamy on August 17, 2014 at 07:41 PM MDT #
Posted by Matt Raible on August 18, 2014 at 04:31 PM MDT #
Gracias, fue muy útil esta información y me solucionó un problema de mas de 2 horas de lucha. Bendiciones !
Thanks, this was very useful information and I solved a problem of more than 2 hours of fighting. Blessings!
Posted by Yerson Crespo on September 05, 2014 at 05:42 PM MDT #
Hi,
To address the dependency issue, I added ng-annotate to your grunt workflow. Here are the Gruntfile.js and package.json files.
Thanks for your blog!
John
package.json:
Gruntfile.js:
Posted by John Horgnies on November 24, 2014 at 11:23 PM MST #
Posted by ej on February 09, 2015 at 02:50 PM MST #
EJ - I tried to reproduce your issue by cloning my repository:
Then I ran "npm install". I ran into some issues here, so I updated package.json. Then I ran "grunt" and it all worked as expected. My "dist/index.html" file looks as follows.
Posted by Matt Raible on February 09, 2015 at 03:04 PM MST #