gulp中连接和uglify js的最佳方法

use*_*781 2 gulp gulp-sourcemaps gulp-concat gulp-uglify

我正在尝试自动化连接和uglify js in gulp.

这是我的gulpfile.js:

gulp.task('compressjs', function() {
    gulp.src(['public/app/**/*.js','!public/app/**/*.min.js'])
    .pipe(sourcemaps.init())
    .pipe(wrap('(function(){"use strict"; <%= contents %>\n})();'))
    .pipe(uglify())
    .pipe(concat('all.js'))
    .pipe(rename({
        extname: '.min.js'
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('public/app'));
})
Run Code Online (Sandbox Code Playgroud)

你是否认为需要包装每个文件(function(){"use strict"; <%= contents %>\n})();以避免在每个文件连接在一起时发生冲突?你认为我的gulp任务是好的,还是可以更好地执行它的任务?

Bae*_*aer 8

对于大多数代码来说,实际上并不需要包含闭包中的每个文件.有一些坏的库存泄漏变量,但我建议你根据具体情况处理它们,如果可能的话,发出Pull Requests来解决问题或者只是停止使用它们.通常它们不能像在函数中包装它们那样简单地修复.

您上面的任务将无法正确地将所有文件传递给uglify任务 - 您需要先连接.您也不需要重命名,因为您可以在concat中指定全名.以下是经过充分测试的Gulp设置,可以完全满足您的要求:

gulp.task('javascript:vendor', function(callback) {
  return gulp.src([
      './node_modules/jquery/dist/jquery.js',
      './node_modules/underscore/underscore.js',
      './node_modules/backbone/backbone.js'
    ])
    .pipe(sourcemaps.init())
    // getBundleName creates a cache busting name
    .pipe(concat(getBundleName('vendor')))
    .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./public/app'))
    .on('error', handleErrors);
});
Run Code Online (Sandbox Code Playgroud)