Google Closure Compiler advanced: remove code blocks at compile time

╄→гoц情女王★ 提交于 2019-12-24 08:28:50

问题


If I take this code and compile it (advanced optimizations)

/**@constructor*/
function MyObject() {
    this.test = 4
    this.toString = function () {return 'test object'}
}
window['MyObject'] = MyObject

I get this code

window.MyObject=function(){this.test=4;this.toString=function(){return"test object"}};

Is there any way I can remove the toString function using the Closure Compiler?


回答1:


toString is implicitly callable, so unless the Closure compiler can prove that the result of MyObject is never coerced to a string it has to preserve it.

You can always mark it as explicit debug code:

this.test = 4;
if (goog.DEBUG) {
  this.toString = function () { return "test object"; };
}

then in your non-debug build, compile with

goog.DEBUG = false;

See http://closure-library.googlecode.com/svn/docs/closure_goog_base.js.source.html which does

/**
 * @define {boolean} DEBUG is provided as a convenience so that debugging code
 * that should not be included in a production js_binary can be easily stripped
 * by specifying --define goog.DEBUG=false to the JSCompiler. For example, most
 * toString() methods should be declared inside an "if (goog.DEBUG)" conditional
 * because they are generally used for debugging purposes and it is difficult
 * for the JSCompiler to statically determine whether they are used.
 */
goog.DEBUG = true;


来源:https://stackoverflow.com/questions/4167519/google-closure-compiler-advanced-remove-code-blocks-at-compile-time

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