开发者

ignore compiler warning from one file in Google Closure

开发者 https://www.devze.com 2023-02-19 14:04 出处:网络
I\'m using an external library (Phonegap) in a fairly large Closure project. Unfortunately Phonegap generates a ton was compiler warnings (all \"dangerous use of 开发者_JS百科this\"). Enough that it m

I'm using an external library (Phonegap) in a fairly large Closure project. Unfortunately Phonegap generates a ton was compiler warnings (all "dangerous use of 开发者_JS百科this"). Enough that it makes searching through the compiler output for warning about my own code pretty annoying.

Is there a way to silence just the warnings from one file?


I suppose you mean type warnings when you are using VERBOSE or checkTypes.

Put the following into any file:

/**
 * @fileoverview
 * @suppress {checkTypes}
 */

to turn off type checking for that file only. You can @suppress many other things as well. Read the Closure Compiler docs for more details.

Dangerous use of "this"

However, if you are talking about "dangerous use of this" warnings, DO NOT ignore them. They refer to places where:

  1. You have a namespace
  2. You defined a function within that namespace
  3. You use "this" inside that function -- and this can refer to the namespace
  4. That namespace may be flattened by the compiler

For example:

foo.bar.hello = "Hello World!";
foo.bar.baz = function() {
   alert(this.hello);
};
foo.bar.baz();    // this --> foo.bar

The "alert" statment will be flagged by a compiler warning of "dangerous use of this". Why? Remember, if the compiler flattens the "foo.bar" namespace:

$foo$bar$hello$ = "Hello World!";
$foo$bar$baz$ = function() { alert(this.$hello$); }
$foo$bar$baz$();   // this --> window

Notice I am using debug variables renaming here. In reality, "$foo$bar$baz" may be renamed just to "a".

You can see immediately that the call to foo.bar.baz() will fail because "this" no longer refers to "foo.bar", but refers to the global object. You code will crash with a loud CRANK!

Exception cases when "this" is OK

Now, there are cases where usage of "this" is OK. For example, in event handlers. "this" will automatically point to the DOM node that raised that event.

In these cases, you need to use the following type of JsDoc directive:

/** @this {Node} */

to specify the type expected for "this" in order to shut the compiler up.


There should be a --warning_level option that you can use with ClosureCompiler.jar

VERBOSE, QUIET, DEFAULT are options.

You should compile the PhoneGap separately with QUIET.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号