创建一个可以成为无操作的打字稿功能

时间:2014-04-23 15:27:07

标签: debugging typescript

我想创建一个TRAP function,在调试模式下,它是"调试器;"在呼叫和发布模式下,它什么也不做,最好不是呼叫/返回。

我想出了:

// declare it
var trap = function () { debugger; }

// ...

// use it
trap();

然后对于发布模式:

var trap = function () { }

所以,问题#1是,这是最好的方法吗?

问题2是,有没有办法做#34; #if DEBUG,#else,#endif"它周围的pragma类型,还是我们在生产时需要手工更改它?

3 个答案:

答案 0 :(得分:3)

我不确定你如何定义" debug"模式完全正确,但如果调试模式不仅仅是编译脚本,那么我通常只是在你已经完成的情况下对函数进行条件化(我已经在许多JavaScript应用程序上工作了,例如我们在哪里即使发布了缩小的脚本以帮助解决生产中的客户问题,它也有一个" debug"模式...它是通过cookie或查询字符串激活的:

// this would be set for example to true when
// in debug mode
export var isDebugModeActive: boolean = false;

export var trap = () => {
    debugger;
};

if (isDebugModeActive) {
    // since you may not want to conditionalize 
    // through a #PRAGMA like system every call to
    // trap, this just no-ops the function
    trap = () => {};
}

// or
trap = () => {
    // checking a boolean is going to be 
    // really fast ... :)
    if (isDebugModeActive) {
        debugger;
    }
}

进行"调试"您希望不经常使用模式,但有时会将其他信息输出到浏览器控制台日志中。

答案 1 :(得分:0)

实现此目的的最简单方法是拥有两个版本的文件 - trap.debug.ts和trap.prod.ts文件。
trap.prod.ts将包含函数定义,然后什么都不做 您应该能够在服务器端使用带有#if DEBUG属性的MVC Bundles或SquishIt来包含脚本的调试或prod版本。
希望这会有所帮助。

答案 2 :(得分:0)

我通过搜索找到了该页面。万一其他人也这样做。这就是我想要的。

type Noop = () => void;
// tslint:disable-next-line:no-empty
const noop: Noop = () => {};

示例用法:

const onPress = (buttons && buttons[0].onPress) || noop;