Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UglifyJS 'use strict' statements

I'm using Grunt hooked up with grunt-contrib-uglify task to minify JavaScript in my app.

Upon minification, it's removing every 'use strict' statement except the very first one, so I'm getting a huge JavaScript file with 'use strict' directive at the top.

The issue is that the global 'use strict' directive makes the browser execute the code of every lib I'm using in the project in the "strict mode" and it's causing errors, since not every 3rd party code is written for strict mode.

Any ideas on how to solve this?

like image 648
Roman Kolpak Avatar asked Dec 19 '13 14:12

Roman Kolpak


1 Answers

If you wrap all your scripts with an IIFE then the grunt-contrib-uglify won't position that statement to the stop and rather it'll leave it inside every IIFE you write.

(function() {
    'use strict';

    // do stuff
})();

Yes, it's more code, but if your gzipping the file it should be a non-issue. Also this will keep any variables you define outside of the global scope, leading to more performant code.

like image 189
Alexander Hripak Avatar answered Nov 21 '22 04:11

Alexander Hripak