如何强制谷歌闭包编译器保持“使用严格”;在编译的js代码中? [英] How to force google closure compiler to keep "use strict"; in the compiled js code?
问题描述
如果您正在使用模块模式并且具有以下内容:
(function(){
use strict;
//这个函数是严格的...
}());
并使用Google Closure Compiler编译代码,use strict ;
指令不会进入编译文件。
那么如何阻止Closure Compiler删除ES5 / strict指令? / p>
(注意我不想使用另一种强制执行ES5 /严格模式的方式,即简单地将use strict;添加到第一行编译文件。我想使用所描述的模块模式这里。)
这不是最好的答案,但就我而言可以说这是封闭编译器的已知问题或功能(取决于您的观点)。以下是部分解释所涉及的一些问题。提到的一点是,当组合多个文件时,无法保留文件级严格模式声明,并且编译器的函数内联功能将破坏函数级严格模式声明的范围。由于使用严格声明的行为在编译代码中是不可预测/错误的(当严格模式被误用于非严格代码时可能会破坏程序),编译器会像其他任何死代码一样剥离它们。
似乎有一个想法是在编译器中完全实现ECMAScript 5严格模式检查(在这种情况下,从编译代码中删除它不会有任何缺点),但它还没有。
编译 SIMPLE_OPTIMIZATIONS
模式而不是 ADVANCED_OPTIMIZATIONS
将禁用死亡代码删除,但我怀疑你已经知道了。
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.)
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.
这篇关于如何强制谷歌闭包编译器保持“使用严格”;在编译的js代码中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!