[英]Closure Compiler doesn't minify functions inside anonymous function
I have this piece of code, compiled from TypeScript to JavaScript, that I want to minify with the Google Closure Compiler: 我有这段从TypeScript编译为JavaScript的代码,我想使用Google Closure Compiler进行简化:
var api;
(function (api) {
function connect() {
console.log("connected!");
}
api.connect = connect;
})(api || (api = {}));
api.connect();
This is compiled to: 编译为:
var a;
(function(b) {
b.connect = function() {
console.log("connected!");
};
})(a || (a = {}));
a.connect();
As you can see, the name of the connect
function inside the anonymous function is not renamed to something like a
or b
. 如您所见,匿名函数内部的
connect
函数的名称未重命名为a
或b
。
How can I tell the compiler to minify the name of the connect
function? 我如何告诉编译器缩小
connect
函数的名称?
EDIT: 编辑:
Seems like this is because connect
is a reserved word. 似乎是因为
connect
是保留字。 When I replace connect
with connectt
, the problem is gone. 当我用
connectt
替换connect
时,问题消失了。
var api;
(function (api) {
function connectt() {
console.log("connected!");
}
api.connectt = connectt;
})(api || (api = {}));
api.connectt();
Compiles to: 编译为:
var a;
(function(b) {
b.a = function() {
console.log("connected!");
};
})(a || (a = {}));
a.a();
Thanks to @A. 感谢@A。 Andres !
安德烈斯!
Some properties won't be renamed because they are declared in an externs file . 有些属性不会重命名,因为它们是在externs文件中声明的。 If the compiler can't decide whether a property is part of an external dependency then it won't be renamed.
如果编译器无法确定某个属性是否属于外部依赖项,则不会重命名该属性。
In your specific case, I can see that there is a method called connect
that is part of the Web Audio API in externs/browser/w3c_audio.js ( AudioNode.prototype.connect
). 在您的特定情况下,我可以看到externs / browser / w3c_audio.js (
AudioNode.prototype.connect
)中有一个名为connect
的方法是Web Audio API的一部分。
Property renaming is explained in great detail in the Closure Compiler FAQ and the blog posts mentioned there. 属性重命名在Closure Compiler FAQ和其中提到的博客文章中进行了详细说明。
The problem is how you are passing your namespace in via an IIFE argument. 问题是如何通过IIFE参数传递名称空间。 If you avoid that, you get the results you want.
如果避免这种情况,您将获得所需的结果。
const api = {};
(function () {
function connect() {
console.log("connected!");
}
api.connect = connect;
})();
api.connect();
The compiler doesn't recognize api
as a type and therefore doesn't have enough information to differentiate the properties from other objects. 编译器无法将
api
识别为类型,因此没有足够的信息来区分属性与其他对象。 By avoiding the alias created by the IIFE call and using const
to tell the compiler that api
is a namespace, you can get the optimizations you seek. 通过避免由IIFE调用创建的别名,并使用
const
告诉编译器api
是一个命名空间,您可以获得所需的优化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.