If you're using the module pattern and have something like this:
(function () { "use strict"; // this function is strict... }());
and compile the code using the Google Closure Compiler, the "use strict";
directive will not make it into the compiled file.
So how do you prevent the Closure Compiler from removing the ES5/strict directive?
(Note that I don't want to use the other mode of enforcing ES5/strict mode, which is to simply add the "use strict"; to the first line of the compiled file. I want to use the module pattern as described here.)
'use strict'; When a JavaScript engine sees this directive, it will start to interpret the code in a special mode. In this mode, errors are thrown up when certain coding practices that could end up being potential bugs are detected (which is the reasoning behind the strict mode).
What is the Closure Compiler? The Closure Compiler is a tool for making JavaScript download and run faster. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left.
Is use strict necessary? The strict mode is no longer required since the release of ES2015, which fixes most of JavaScript's confusing behavior with a more robust syntax. It's just good to know because you might find it in legacy projects that still used it.
Update: strict mode is now supported in the compiler.
Just use --language_in=ECMASCRIPT5_STRICT
.
References:
http://code.google.com/p/closure-compiler/issues/detail?id=69
http://code.google.com/p/closure-compiler/source/detail?r=873
http://code.google.com/p/closure-compiler/source/detail?r=1114
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With