在gulp中连接和丑化js的最佳方式



我正在尝试进行自动化以在gulp中连接和丑化js。

这是我的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'));
})

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

对于

大多数代码来说,将每个文件包装在闭包中确实不是必需的。有一些糟糕的库会泄漏变量,但我建议您根据具体情况处理它们,如果可能的话,发出拉取请求来解决问题或停止使用它们。通常,它们不能像将它们包装在函数中那样简单地修复。

您上面的任务不会将所有文件正确传递给 uglify 任务 - 您需要先连接。您也不需要重命名,因为您可以在连接中指定全名。下面是一个经过良好测试的 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);
});

最新更新