Matt RaibleMatt Raible is a Web Developer and Java Champion. Connect with him on LinkedIn.

The Angular Mini-Book The Angular Mini-Book is a guide to getting started with Angular. You'll learn how to develop a bare-bones application, test it, and deploy it. Then you'll move on to adding Bootstrap, Angular Material, continuous integration, and authentication.

Spring Boot is a popular framework for building REST APIs. You'll learn how to integrate Angular with Spring Boot and use security best practices like HTTPS and a content security policy.

For book updates, follow @angular_book on Twitter.

The JHipster Mini-Book The JHipster Mini-Book is a guide to getting started with hip technologies today: Angular, Bootstrap, and Spring Boot. All of these frameworks are wrapped up in an easy-to-use project called JHipster.

This book shows you how to build an app with JHipster, and guides you through the plethora of tools, techniques and options you can use. Furthermore, it explains the UI and API building blocks so you understand the underpinnings of your great application.

For book updates, follow @jhipster-book on Twitter.

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 7 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 09: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 07:41 PM MDT #

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

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:

{
    "name": "Planning",
    "version": "0.5.1",   
    "dependencies": {},
    "devDependencies": {
        "grunt": "~0.4.2",
        "grunt-contrib-concat": "~0.3.0",
        "grunt-contrib-uglify": "~0.2.7",
        "grunt-contrib-cssmin": "0.10.0",
		"grunt-usemin": "~2.0.2",
		"grunt-contrib-copy": "~0.5.0",
		"grunt-rev": "~0.1.0",
		"grunt-contrib-clean": "~0.5.0",
		"grunt-ng-annotate": "^0.4.0"
    }
}

Gruntfile.js:

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/'
            },
            tmp: {
                expand: true,
                cwd: 'app/',
                src: ['**', '!js/**', '!lib/**'],
                dest: 'tmp/'
            }
        },
 
        rev: {
            files: {
                src: ['dist/**/*.{js,css}', '!dist/js/shims/**']
            }
        },
 
        useminPrepare: {
            html: 'tmp/index.html'
        },
 
        usemin: {
            html: ['dist/index.html']
        },
 
        uglify: {
            options: {
                report: 'min',
                mangle: true
            }
        },
	ngAnnotate: {
            options: {
                singleQuotes: true,
            },
            app: {
                files: [
                    {
                        expand: true,
                        cwd: 'app/js',
                        src: '*.js', 
                        dest: 'tmp/js',   // Destination path prefix
                        ext: '.js', // Dest filepaths will have this extension.
                        extDot: 'last',       // Extensions in filenames begin after the last dot
                    },
                ],
            }
        }
    });
 
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-ng-annotate');
    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', 'ngAnnotate', 'useminPrepare', 'concat', 'uglify', 'cssmin', 'rev', 'usemin'
    ]);
};

Posted by John Horgnies on November 24, 2014 at 11:23 PM MST #

this works great, but now in the 'dist/index.html' file all the old script tags are left there even though they've all been concatenated into app.js, causing lots of 404 errors. is there a way to force usemin to remove the unused tags of scripts that have been concat'd?

Posted by ej on February 09, 2015 at 02:50 PM MST #

EJ - I tried to reproduce your issue by cloning my repository:

git clone https://github.com/mraible/angular-seed.git

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.

<!doctype html>
<html lang="en" ng-app="myApp">
<head>
  <meta charset="utf-8">
  <title>My AngularJS App</title>
  <link rel="stylesheet" href="css/f050d0dc.seed.min.css"/>
</head>
<body>
  <ul class="menu">
    <li><a href="#/view1">view1</a></li>
    <li><a href="#/view2">view2</a></li>
  </ul>

  <div ng-view></div>

  <div>Angular seed app: v<span app-version></span></div>

  <script src="js/8973cf0f.seed.min.js"></script>
</body>
</html>

Posted by Matt Raible on February 09, 2015 at 03:04 PM MST #

Post a Comment:
  • HTML Syntax: Allowed