How to force google closure compiler to keep “use

2019-02-01 11:33发布

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.)

5条回答
贼婆χ
2楼-- · 2019-02-01 11:58

Strict mode is useful for debugging, and not much else until it sees adoption into every major browser. By the time Closure Compiler removes the tag it's era of being useful is over anyway. I'm sure they'll update the compiler to allow preserving the tag long before that feature will actually be useful.

查看更多
劫难
3楼-- · 2019-02-01 12:02
淡お忘
4楼-- · 2019-02-01 12:03

You use the compiler's output wrapper to create the module wrapper and include the "use strict" directive there.

查看更多
闹够了就滚
5楼-- · 2019-02-01 12:15

This isn't the greatest answer, but as far as I can tell this is a known issue or "feature" (depending on your perspective) of closure compiler. Here's a partial explanation of some of the problems involved. A couple mentioned are that there's no way to preserve file-level strict mode declarations when multiple files are combined, and the compiler's function inlining feature would break the scope of function-level strict mode declarations. Since the behavior of "use strict" declarations would be unpredictable/wrong in compiled code (potentially breaking programs when strict mode is misapplied to non-strict code), the compiler strips them like any other dead code.

There seems to have been an idea to fully implement ECMAScript 5 strict mode checks in the compiler (in which case there would be no downside to removing it from compiled code), but it's not there yet.

Compiling in SIMPLE_OPTIMIZATIONS mode instead of ADVANCED_OPTIMIZATIONS will disable dead code removal, but I suspect you already know that.

查看更多
老娘就宠你
6楼-- · 2019-02-01 12:21

Dangerous. Closure Compiler in Advanced mode is not strict-mode compatible, which means that the compiler will rewrite code based on ECMAScript 262 rev 3 rules. Some rules are changed for strict-mode (e.g. "this" binding in anonymous functions, scope resolution etc.) that will cause code breakage if Closure Compiler rewrites code incorrectly due to wrong language assumptions.

The short answer (and the Closure Compiler's official answer) is: don't do it.

If you really just want to shovel a "use strict" string there, try:

eval('"use strict";');
查看更多
登录 后发表回答