简体   繁体   English

Google闭包编译器抱怨typeof调用中的未声明变量

[英]Google closure-compiler complaining about undeclared variable in typeof call

I am minifying JavaScript for a typical modern browser (eg. Chrome 64) using Google's closure-compiler v20180101. 我正在使用Google的闭包编译器v20180101缩小典型现代浏览器(例如Chrome 64)的JavaScript。 The same code compiled without errors for v20170409. v20170409的相同代码编译没有错误。 I am using the same piece of JS in multiple a several different packaging contexts and would rather not split things into many tiny files. 我在多个不同的包装环境中使用同一块JS,而宁愿不将其拆分为许多小文件。

Instead, I've added some conditional code that uses typeof to see if some functions are already defined and if not, define them. 相反,我添加了一些使用typeof条件代码,以查看是否已经定义了某些函数,如果尚未定义,请对其进行定义。

This is a very basic example: 这是一个非常基本的示例:

if (typeof foo === 'undefined') {
  foo = function() { return "Foo!"; }
}

In response to this, clojure-compiler-v20180101 complains of: 对此,clojure-compiler-v20180101抱怨:

foo.js: ERROR - variable foo is undeclared

I can add an extern file that declares var foo , but this seems to defeat the purpose of the typeof check. 我可以添加一个声明var foo的extern文件,但这似乎typeoftypeof检查的目的。 Also, in other situation foo gets declared twice which closure-compiler also complains about. 另外,在其他情况下, foo被声明两次,而闭包编译器也会抱怨。

Thanks in advance for any assistance. 在此先感谢您的协助。

You need to declare the variable: 您需要声明变量:

/** @suppress {duplicate} */
var foo;
if (typeof foo === 'undefined') {
  foo = function() { return "Foo!"; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM