What is the best way to export library method, when using Closure Compiler?

断了今生、忘了曾经 提交于 2019-12-23 19:08:42

问题


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
  }  
}

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;

And this line to the externs file:

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

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?


回答1:


If you use JSDoc consistently, you could use the @export tag:

/**
* @param {String} str
* @export
*/ 
Lib.prototype.invoke = function(str){
     //this function is called from outside to invoke some of Lib's events
};

and call the compiler with the --generate_exports flag.

This requires you to either include base.js from the Google Closure library, or to copy goog.exportSymbol and goog.exportProperty to your codebase.




回答2:


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.



来源:https://stackoverflow.com/questions/9111900/what-is-the-best-way-to-export-library-method-when-using-closure-compiler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!