Skip to content

Instantly share code, notes, and snippets.

@cwilby
Last active November 28, 2016 19:09
Show Gist options
  • Save cwilby/a0d505023e6aea0be7e32a7ba29fd753 to your computer and use it in GitHub Desktop.
Save cwilby/a0d505023e6aea0be7e32a7ba29fd753 to your computer and use it in GitHub Desktop.

Writing minification safe Angular code

The biggest reason we minify code before deploying to a live web server is that it reduces the overall size of our website.

However, minification can be dangerous if your code is not "minification safe".

This gist serves as an example of what can happen if you do not write "minification safe" Angular code.

Minification Safe

(function() {
    'use strict';

    angular
        .module('app')
        .controller('HomeController', HomeController); // <-- moved from here...

	// Good: Use $inject to specify dependencies (such as $http, $timeout, toastr) as strings to avoid minification issues.
    HomeController.$inject = ['$http']; 

	// ... to here!
    function HomeController($http) {

        $http
          .get('http://www.google.com')
          .then(function(response) {
            console.log(response);
          });
          
    }
})();

Minified

!function(){"use strict";function o(o){o.get("http://www.google.com").then(function(o){console.log(o)})}angular.module("app").controller("HomeController",o),o.$inject=["$http"]}();

Minified with line breaks

!function(){
	"use strict";
	
	function o(o){
		o // <--- retains meaning because we used $inject...
			.get("http://www.google.com")
			.then(function(o) {
				console.log(o)
			});
	}
	
	angular
		.module("app")
		.controller("HomeController",o)
		
	o.$inject=["$http"] // <--- ... here!
}();

Not Minification Safe

var app = angular.module('app', []);

// Bad: $http will lose meaning once minified
app.controller('HomeController', function($http) {

  $http
    .get('http://www.google.com')
    .then(function(response) {
      console.log(response);
    });
    
});

Minified

var app=angular.module("app",[]);app.controller("HomeController",function(o){o.get("http://www.google.com").then(function(o){console.log(o)})});

Minified with line breaks

var app=angular.module("app",[]);

// Bad: $http has lost meaning now that is has been renamed to `o`
app.controller("HomeController",function(o) {
	
	o
		.get("http://www.google.com")
		.then(function(o) {
			console.log(o)
		})
		
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment