zhekaus
zhekaus

Reputation: 3194

How to get rid of unnecessary debugging code in JavaScript during the compilation/minification process?

I used to write lots of debug code in the JavaScript app and I’m looking for a technique that allows to get rid of debug code during the compilation/minification process.

Is there in JavaScript World some equivalent of compilation directives in C/C++?

In C/C++ it looks like this:

#ifdef _DEBUG
counter++;
#endif

PS. Currently, I use gulp

Upvotes: 0

Views: 313

Answers (3)

PilotInPyjamas
PilotInPyjamas

Reputation: 987

Probably academic, but here's an answer which is pure JavaScript. You can use something like this to strip some functions from your code completely, and depending on your compiler, will compile to nothing.

/** @const */
var NDEBUG = false; // change to true for production
var assert = (() => NDEBUG ? () => {}: test => console.assert(test(), test.toString()))();

If NDEBUG == true then assert becomes an empty function: () => {}, otherwise if NDEBUG == false, it takes a function as an argument, calls that function and tests the result.

Usage:

var divideByResult = function (a, b) {
    assert (() => b() !== 0);
    return a() / b();
}

This works like a C style assert. The function inside the assert only gets called if NDEBUG == false. We pass a function to assert rather than an expression. If we passed an expression, the expression b() !== 0 may have side effects and will be evaluated. This way, we guarantee that the expression inside the assert is never evaluated in production code, and an optimising compiler can safely remove the assert as dead code.

Upvotes: 0

Thomas Sebastian
Thomas Sebastian

Reputation: 1612

strip-debug

Strip console, alert, and debugger statements from JavaScript code

Useful for making sure you didn't leave any logging in production code.

Also available as gulp/grunt/broccoli plugins.

Usage

$ npm install --save strip-debug

var stripDebug = require('strip-debug');

stripDebug('function foo(){console.log("foo");alert("foo");debugger;}').toString();
//=> function foo(){void 0;void 0;}   

Usage with gulp

var gulp = require('gulp');
var stripDebug = require('gulp-strip-debug');

gulp.task('default', function () {
    return gulp.src('src/app.js')
        .pipe(stripDebug())
        .pipe(gulp.dest('dist'));
});  

For more details check this: link, and this one for use with gulp: link

Upvotes: 1

Zamboney
Zamboney

Reputation: 2010

i think what you are trying to do is available using a task runner such as grunt or gulp. both of this tools are a task runner that convert your code, using plugin, to do this kind of manipulation.

such of this so called "plugin" is gulp-preprocess. this plugin doing what you are asking :)

for more understand of gulp you can go to the gulp site or find some good tutorials on the web...

Upvotes: 1

Related Questions