Using gulp-diff to discover which of your Javascript won’t minify

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com, or follow me on Twitter.

I am astounded that the tech industry thinks this is a problem worth having. Do we really need any more evidence that HTTP and HTML and Javascript have failed and should be replaced with a new protocol?

Unfortunately, this is a generic problem with minifying code in JavaScript. Because JavaScript is untyped, it is easy to introduce errors in minification like this when variable names are counted on not changing. I personally think programming like this is an anti-pattern but I’m sure the AngularJS team had their reasons and tradeoffs to consider.

The Often Used Workaround For This Minification Problem

The problem has been around for a while and the mitigation for it has been for the community to write a plugin call ngAnnotate. Basically, by putting the gulp plugin ngAnnotate into the minification workflow (or stream), this plugin attempts to patch up any missing dependency injection definitions so that the minification process will yield correctly working code. An example of a gulp file that does this is as follows:

gulp.task('scriptsangular', function () {
    return gulp.src('app.js')
        .pipe(ngAnnotate())   // this steps fixes DI declarations
        .pipe(gulp.dest('dist'))
        .pipe(rename({suffix: '.min'}))
        .pipe(uglify())
        .pipe(gulp.dest('dist'));
});

Personally, I don’t like this solution. My primary objection is that the code that is now being minified is no longer your original code but code that has been modified. It seems to me that this is just stepping down the rat hole that AngularJS stepped down when they tried to automatically deal with the Dependency Injection themselves.

To be completely fair, you can turn off the AngularJS behavior where it injects the dependency for you by adding the attribute ng-strict-di to a div tag surrounding your application (see the comments in this Stack Overflow post). My feeling again is that since this is such an obscure attribute that likely no one will ever find it and use it so it might as well not even be there.

Post external references

  1. 1
    https://www.voxxed.com/blog/2015/01/a-precise-prescription-for-using-angularjs-dependency-injection/
Source