gulp-uglify 可以删除 console.log 语句吗?

Can gulp-uglify strip out console.log statements?

如问题所述。我知道 gulp-uglify 可以用一个简单的方式进行 uglify:

gulp.src('filename')
.pipe(uglify())

有没有办法让它也去掉 console.log 语句?

是的,有! 正如 gulp-uglifyjs 文档中提到的,您可以传递额外的选项(gulp-uglifyjs documentation):

uglify([filename], [options])

所有可用的选项都可以在 the compressor UglifyJS documentation page 上找到。从那个 'drop_console: true' 应该帮助:

uglify([filename], {
    compress: {
         drop_console: true
    }
})

更好的是:您可以使用专门的 gulp 插件:gulp-strip-debug。它不仅去除了控制台语句,还去除了警报和调试器语句。

Strip console, alert, and debugger statements from JavaScript code with strip-debug

使用以下方式安装:

npm install --save-dev gulp-strip-debug

并像这样使用它:

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

gulp-uglify (not gulp-uglifyjs) you can remove arbitrary code by using a strategy similar to compilations constants with the compression configuration(Link转到gulp-uglifyjs,但对于[=应该是相同的29=]-丑化):

.pipe(uglify({
    compress: {
        global_defs: {
            "DEBUG": false
        }
    }
}))

然后在你的代码中写一些类似

的东西
if (DEBUG)
{
    console.log("Application started...");
    //...
}

如果您将 global_defs 中的 DEBUG 设置为 true,gulp-uglify 将删除条件但保留内部分支。如果 DEBUG 设置为 false,它将同时删除两者。

drop_console gulp-uglify 似乎不支持 Fill 的回答。