如何使用 Google Closure API 移除调试代码

How to remove debug code with Google Closure API?

本文关键字:调试 代码 API 何使用 Google Closure      更新时间:2023-09-26

Google闭包文档(查找ENABLE_DEBUG var)解释了如何通过将标志定义--define='ENABLE_DEBUG=false'传递给编译器来更改变量。 Google Closure API 不支持define选项。同时,wiki表示REST服务(和API?)支持debug选项。但是如何在代码中使用它呢?创建 per 变量无济于事,它保持不变:

/** @define {boolean} */
var debug = true;

你可以做什么的例子:

/** @define {boolean} */
var MY_DEBUG = false;
if (MY_DEBUG){
    debuga = function(myparam, myparam2){
        console.log(myparam, myparam2);
        // Big debug stuff..
    };
    debugb = function(myparam, myparam2){
        console.log(myparam, myparam2);
        // Big debug stuff..
    };
}
else{
    debuga = function(myparam, myparam2){};
    debugb = function(myparam, myparam2){};
}
debuga("Hello","World");

您可以使用定义--define='MY_DEBUG=false'来控制MY_DEBUG的值

结果如下

// SIMPLE_OPTIMIZATION            // ADVANCED_OPTIMIZATION
var DEBUG=!1;                     debuga=function(){};
debuga=function(a,b){};           debugb=function(){};
debugb=function(a,b){};           debuga("Hello","World");
debuga("Hello","World");

如果您使用的是闭包库支持,则可以包含CLOSURE_DEFINES的定义以及发送到编译器的源代码的重置。

要查看此操作,您可以执行以下操作:

http://closure-compiler.appspot.com/home

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @use_closure_library true
// ==/ClosureCompiler==
var CLOSURE_DEFINES = {
  'FOO' : true
}
/** @define {boolean} */
var FOO = false;
if (FOO) {
  alert('me');
}

这导致:

alert("me");