如何识别 js 是否是闭包编译的

How to identify if js is closure compiled

本文关键字:是否是 闭包 编译 js 何识别 识别      更新时间:2023-09-26

我有一些javascript项目的源代码,我想知道其中哪些是使用Google的Closure编译器编译的。

您可以查找一些可能是闭包编译器独有的怪癖:

(1) 闭包编译器将所有 "while" 循环重写为 "for" 循环。 因此,如果您看到"while"循环,则闭包编译器未对其进行优化(它可能仍由闭包编译器处理,但尚未优化)

(2) 使用默认优化选项,闭包编译器在大约 500 个字符处换行。 如果平均行长明显小于或大于该值,则编译器可能无法对其进行优化。

(3)一些常量,编译器重写"undefined","true"和"false"分别重写为"void 0"!0"和"!1",如果您看到其他常量,则闭包编译器不会对其进行优化(但不告诉您它已经优化)。

可能存在其他特征,但这取决于您使用的编译器的版本。

我认为

没有可靠的方法可以知道源代码是否使用Google闭包编译器进行压缩。但是,作为一般测试,您可能会尝试重新压缩代码并比较前后结果。这假设使用了简单的优化。

运行下面的示例,结果返回 oiginalSize = 26 和 compressedSize = 21,因为删除了多余的空格。

有关使用该服务的详细信息,请参阅闭包编译器服务 API 参考。 祝你好运!

function compress() {
	var xhr = new XMLHttpRequest();
	xhr.open('POST', 'https://closure-compiler.appspot.com/compile', false);
	xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	xhr.send( 
   		'compilation_level=SIMPLE_OPTIMIZATIONS&' +
   		'output_info=errors&' +
   		'output_info=statistics&' +
   		// 'output_info=compiled_code&' +
   		'output_format=json&' +
   		'js_code=' + encodeURIComponent( document.getElementById('input1').value )
   	);
   	document.getElementById('output1').value = xhr.responseText;
} 
textarea { width:100%; height:2em; padding:0.5em; border:1px black solid; margin-bottom:2em; }
Paste your code and click button<p>
<button onclick="compress()">Compress</button>
<textarea id="input1">
alert(  "hello world"  );
</textarea>
output:
<textarea id="output1"></textarea>