Using Gulp to Concatenate and Uglify files

后端 未结 6 2210
一生所求
一生所求 2020-11-27 09:39

I\'m trying to use Gulp to:

  1. Take 3 specific javascript files, concatenate them, then save the result to a file (concat.js)
  2. Take this concatenated file
6条回答
  •  天涯浪人
    2020-11-27 10:18

    It turns out that I needed to use gulp-rename and also output the concatenated file first before 'uglification'. Here's the code:

    var gulp = require('gulp'),
        gp_concat = require('gulp-concat'),
        gp_rename = require('gulp-rename'),
        gp_uglify = require('gulp-uglify');
    
    gulp.task('js-fef', function(){
        return gulp.src(['file1.js', 'file2.js', 'file3.js'])
            .pipe(gp_concat('concat.js'))
            .pipe(gulp.dest('dist'))
            .pipe(gp_rename('uglify.js'))
            .pipe(gp_uglify())
            .pipe(gulp.dest('dist'));
    });
    
    gulp.task('default', ['js-fef'], function(){});
    

    Coming from grunt it was a little confusing at first but it makes sense now. I hope it helps the gulp noobs.

    And, if you need sourcemaps, here's the updated code:

    var gulp = require('gulp'),
        gp_concat = require('gulp-concat'),
        gp_rename = require('gulp-rename'),
        gp_uglify = require('gulp-uglify'),
        gp_sourcemaps = require('gulp-sourcemaps');
    
    gulp.task('js-fef', function(){
        return gulp.src(['file1.js', 'file2.js', 'file3.js'])
            .pipe(gp_sourcemaps.init())
            .pipe(gp_concat('concat.js'))
            .pipe(gulp.dest('dist'))
            .pipe(gp_rename('uglify.js'))
            .pipe(gp_uglify())
            .pipe(gp_sourcemaps.write('./'))
            .pipe(gulp.dest('dist'));
    });
    
    gulp.task('default', ['js-fef'], function(){});
    

    See gulp-sourcemaps for more on options and configuration.

提交回复
热议问题