如何在compilation/minification过程中去除JavaScript中不必要的调试代码?

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

我曾经在 JavaScript 应用程序中编写大量调试代码,我正在寻找一种技术,可以在 compilation/minification 过程中删除调试代码。

在 JavaScript 世界中是否有一些等同于 C/C++ 中的编译指令?

在 C/C++ 中看起来像这样:

#ifdef _DEBUG
counter++;
#endif

PS。目前,我使用 gulp

我认为您可以使用诸如 gruntgulp 之类的任务运行器来实现您正在尝试执行的操作。这两个工具都是一个任务运行器,可以使用插件转换您的代码以执行此类操作。

所谓的"plugin"就是gulp-preprocess。这个插件可以满足您的要求:)

要进一步了解 gulp,您可以访问 gulp 站点或在网上找到一些好的教程...

剥离调试

Strip console, alert, and debugger statements from JavaScript code

有助于确保您没有在生产代码中留下任何日志记录。

也可用作 gulp/grunt/broccoli 插件。

用法

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

与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'));
});  

有关详细信息,请查看:link, and this one for use with gulp: link

可能是学术性的,但这是一个纯粹的答案 JavaScript。您可以使用类似这样的东西从您的代码中完全剥离一些功能,并且根据您的编译器,将编译为空。

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

如果 NDEBUG == true 则 assert 变为空函数:() => {},否则如果 NDEBUG == false,它接受一个函数作为参数,调用该函数并测试结果。

用法:

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

这类似于 C 风格的断言。断言中的函数仅在 NDEBUG == false 时被调用。我们将函数传递给断言而不是表达式。如果我们传递了一个表达式,表达式 b() !== 0 可能会有副作用并且会被计算。这样,我们保证断言中的表达式永远不会在生产代码中求值,并且优化编译器可以安全地将断言作为死代码删除。