【问题标题】:How do I tell the closure compiler to ignore code?如何告诉闭包编译器忽略代码?
【发布时间】:2013-07-16 20:07:54
【问题描述】:

我决定在实现接口时需要一些帮助。于是我在闭包库的base.js文件中加入了这个函数。

/**
 * Throws an error if the contructor does not implement all the methods from 
 * the interface constructor.
 *
 * @param {Function} ctor Child class.
 * @param {Function} interfaceCtor class.
 */
goog.implements = function (ctor, interfaceCtor) {
    if (! (ctor && interfaceCtor))
    throw "Constructor not supplied, are you missing a require?";
    window.setTimeout(function(){
        // Wait until current code block has executed, this is so 
        // we can declare implements under the constructor, for readability,
        // before the methods have been declared.
        for (var method in interfaceCtor.prototype) {
            if (interfaceCtor.prototype.hasOwnProperty(method)
                && ctor.prototype[method] == undefined) {
                throw "Constructor does not implement interface";
            }
        }
    }, 4);
};

现在,如果我声明我的类实现了一个接口但没有实现该接口的所有方法,这个函数将抛出一个错误。从最终用户的角度来看,这绝对没有任何好处,它只是帮助开发人员的一个很好的补充。因此,我如何告诉闭包编译器在看到以下行时忽略它?

goog.implements(myClass, fooInterface);

有可能吗?

【问题讨论】:

  • 为什么不直接运行带有 AO 的生产版本并让编译器给你这个反馈?
  • 希望 AO 完全去除不需要的代码。

标签: javascript google-closure-compiler google-closure google-closure-library


【解决方案1】:

这取决于您所说的忽略。你想让它编译成什么都没有,以便它只在未编译的代码中工作?如果是这样,您可以使用标准的@define 值之一:

goog.implements = function (ctor, interfaceCtor) {
  if (!COMPILED) {
    ...
  }
};

或者,仅当 goog.DEBUG 启用时:

goog.implements = function (ctor, interfaceCtor) {
  if (goog.DEBUG) {
    ...
  }
};

如果这些不合适,您可以自己定义。

或者你的意思完全不同?

【讨论】:

  • 这可以解决问题,我只是在它编译时没有执行函数中的循环和其他代码。为用户稍微加快速度。谢谢。
猜你喜欢
  • 2014-03-11
  • 2010-09-09
  • 2020-12-29
  • 2011-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
相关资源
最近更新 更多