Lien
Lien

Reputation: 515

how to use Gulp to concat different js with different set of js , then pipe minify/uglify to different bundle?

what I want to archive with Gulp is:

  1. For example I am currently editing editing.js
  2. If it has been changed/saved, then take base1.js,base2.js,base3.js out, concat them with my editing.js in order like base1.js,base2.js,base3.js,editing.js
  3. Minify and uglify them
  4. Finally rename this file with extension like 'editing.min.js'.

    gulp.task('minify-js', function(){
        gulp.src('static/src/*.js')
            .pipe(concat('static/src/base.js'))
            .pipe(uglify())
            .pipe(gulp.dest('static/dist'));
    });
    

And in my case I have multiple source file to be concatenated to multiple bundled files.

What I am failing to archive is to rename to the filename I am currently editing, e.g ex1.js to ex1.min.js, it always bundled into one only file.

New to Gulp, hope some help, thanks!!

Upvotes: 0

Views: 805

Answers (1)

robertklep
robertklep

Reputation: 203534

If I understand correctly, something like this should do it:

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

gulp.task('minify-js', function() {
  return gulp.src([ 'static/src/*.js', 'editing.js' ])
             .pipe(concat('editing.min.js'))
             .pipe(uglify())
             .pipe(gulp.dest('static/dist/'));
});

As you can see, there's no need to rename because gulp-concat already requires you to specify an output filename.

EDIT: here's another take. It watches for changes to any .js files (with some exclusions; instead of using **/*.js you may be able to specify a particular directory where your source files live to limit to amount of possible matches). When a file changes, it will concatenate the base*.js files and the file that was changed, and use the filename of the changed file as a base for the minified filename (foo.jsfoo.min.js):

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

gulp.task('minify-js', function() {
  // Watch for changes on JS files, but exclude some of them.
  return gulp.watch([ 
    '**/*.js', 
    '!static/src/base*.js',
    '!node_modules/',
  ], function(ev) {
    // Watch for changes to the files.
    if (ev.type !== 'changed') return;

    // Determine 'minified' filename.
    var basename = path.basename(ev.path);
    var extname  = path.extname(basename);
    var minname  = basename.replace(extname, '.min' + extname);

    // Run the uglify chain.
    return gulp.src([ 'static/src/base*.js', ev.path ])
        .pipe(concat(minname))
        .pipe(uglify())
        .pipe(gulp.dest('static/dist/'));
  });
});

Upvotes: 1

Related Questions