70

I am new to Gulp and wondering how can I minify (concatinate) my collection to single file instead of every file separately.

Example

var gulp = require('gulp');
var uglify = require('gulp-uglify');

gulp.task('minify', function () {
   gulp.src([
        'content/plugins/jquery/jquery-2.1.1.js',
        'content/plugins/jquery/jquery-ui.js',
        'content/js/client.js'])
      .pipe(uglify())
      .pipe(gulp.dest('content/js/client.min.js')) // It will create folder client.min.js
});

gulp.task('default', ['minify']);

As you can see I'm trying to minify 3 javascript files and then output them into one client.min.js. Is it possible?

Stan
  • 25,744
  • 53
  • 164
  • 242

3 Answers3

107

This plugin will help gulp-concat.

Usage:

var concat = require('gulp-concat');

gulp.task('scripts', function() {
  gulp.src(['./lib/file3.js', './lib/file1.js', './lib/file2.js'])
    .pipe(concat('all.js'))
    .pipe(uglify())
    .pipe(gulp.dest('./dist/'))
});
user3995789
  • 3,452
  • 1
  • 19
  • 35
  • 5
    so uglify does js minification by default? – George Pligoropoulos May 27 '15 at 17:39
  • Does this also work for concatenating and minifying css and html files? – CSS Aug 10 '15 at 20:54
  • @IamC.S.S. Yes, the same approach should work, but instead of uglify you need eg. `gulp-minify-css`. – tuomassalo Sep 02 '15 at 09:51
  • Better to uglify first (all files will be minified separately, one by one), then concat. This lets to avoid some of problems in resulting script. Variant 2 - concat with some glue Variant 3 - use Google closure compiler to do both task. – SynCap Aug 24 '16 at 11:31
  • If I would have a `require` from file1.js to file3.js it would not work, right? (in file1.js `require("./file3")`) – peni4142 Dec 12 '18 at 15:45
  • If I grouped files, How do I access the function of each files for UnitTesting using Mocha. – Vineesh TP Apr 20 '20 at 04:54
12

Instead of going through a lots of tricky things, I recommend you getting laravel-elixir. It is compiling sass, less, babel, coffescript and even adding something that you want with not just JavaScript but also with css. All the code that you will need will be:

var gulp = require('gulp');
var elixir = require('laravel-elixir');

elixir(function(mix) {
    mix.scripts(['app.js', 'controllers.js', 'sweetalert.js'], 'public/js/all.js');
    mix.styles(['normalize.css', 'app.css', 'sweetalert.css'], 'public/css/all.css')
});
Aditya Giri
  • 1,786
  • 18
  • 33
3

Lets try gulp-concat-util for joining scripts. It's similar to concat, but have some helpers to glue files. There is special helper to concatinate scripts.

var concat = require('gulp-concat-util');

gulp.task('scripts', function() {
  gulp.src(['./lib/file3.js', './lib/file1.js', './lib/file2.js'])
    .pipe(concat.scripts('all.js'))
    .pipe(uglify())
    .pipe(gulp.dest('./dist/'))
});
SynCap
  • 6,244
  • 2
  • 18
  • 27