使用Closure Compiler时,导出库方法的最佳方法是什么? [英] What is the best way to export library method, when using Closure Compiler?

查看:96
本文介绍了使用Closure Compiler时,导出库方法的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Closure Compiler文档明确指出:不要使用Externs而不是Exports.因为Externs非常易于使用,所以我遇到了一个问题:

Closure Compiler documentation clearly states: "Don't use Externs instead of Exports". Because Externs are very handy to use, I came down with a problem:

function Lib(){ 
  //some initialization  
}
Lib.prototype = {
  invoke : function(str){
     //this function is called from outside to invoke some of Lib's events
  }  
}

当将Closure Compiler与 ADVANCED_OPTIMIZATIONS 一起使用时,函数调用将从源中删除.可以通过两种方式防止这种情况: 在原型定义之后添加行:

When using Closure Compiler with ADVANCED_OPTIMIZATIONS, function invoke is removed from the source. This could be prevented in two ways: Adding the line after prototype definition:

Lib.prototype['invoke'] = Lib.prototype.invoke;

但这在输出代码的末尾增加了丑陋的代码和平度:

But this adds an ugly peace of code at the end of the output code:

Lib.prototype.invoke = Lib.prototype.g;

我设法通过将以下行添加到构造函数中来摆脱这种情况:

I managed to get rid of this by adding this line to the constructor:

this.invoke = this.invoke;

这是externs文件的这一行:

And this line to the externs file:

/**
* @param {String} str
*/ 
Lib.prototype.invoke = function(str){};

通过这种方式,Closure Compiler无法从输出代码中删除调用函数,因为它是在构造函数中由其自身分配的,而且,由于在externs文件中定义了它,因此它也不能对其进行重命名. 那么女巫的方法更好吗?

This way, Closure Compiler can't remove invoke function from the output code, because it is assigned by itself in the constructor, and also, it can't rename it, because it is defined in the externs file. So witch method is better?

推荐答案

我个人喜欢在externs文件中定义接口并让我的内部类实现它们.

Personally, I like defining interfaces in externs file and having my internal classes implement them.

// Externs

/** @interface */
function IInvoke {};
IInvoke.prototype.invoke;

/** 
 *  @constructor
 *  @implements {IInvoke}
 */
function Lib(){ 
  //some initialization  
}
Lib.prototype = {
  invoke : function(str){
     //this function is called from outside to invoke some of Lib's events
  }  
}

您仍然导出构造函数本身,但不导出接口方法.

You still export the constructor itself, but not the interface methods.

这篇关于使用Closure Compiler时,导出库方法的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆