I want to create a TRAP function where in debug mode it is the "debugger;" call and in release mode it does nothing, preferably not even a call/return.

I have come up with:

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

// ...

// use it
trap();

And then for release mode it's:

var trap = function () { }

So, question #1 is, is this the best way to do this?

And question #2 is, is there a way to do an "#if DEBUG , #else, #endif" type of pragmas around it, or do we need to change it by hand when we build for production?

有帮助吗?

解决方案

I'm not sure how you define "debug" mode exactly, but if debug mode is more than just what scripts are compiled then I'd generally just conditionalize the function as you've done (I've worked on a number of JavaScript apps for example where we have had a "debug" mode even when the minified scripts were released to help with customer issues in production ... it was activated either through a cookie or a query string):

// 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;
    }
}

Having a "debug" mode works well when you want to infrequently, but sometimes output additional information to the browser console log for example.

其他提示

I found this page by search. In case others do too. This is what I was looking for.

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

Example use:

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

The simplest way of accomplishing this would be to have two versions of your file - a trap.debug.ts and a trap.prod.ts file.
trap.prod.ts would include the function definition, and then do nothing.
You should be able to use MVC Bundles or SquishIt on the server side with a #if DEBUG attribute to include the debug or prod version of your script.
Hope this helps.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top