0

I'm trying to do the following in Gulp: 1) Minify JS files from a specified folder to a folder called 'dist'. 2) Append '.min' to the minified filenames. 3) Provide a sourcemap to the minified files and place them in a folder called 'maps'.

I am using 'gulp-uglify', 'gulp-rename' and 'gulp-sourcemaps'.

Here is what I have:

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

gulp.task('compress', function () {
    gulp.src('src/*.js')
    .pipe(sourcemaps.init())
    .pipe(uglify())
    .pipe(rename({suffix: '.min'}))
    .pipe(sourcemaps.write('../maps'))
    .pipe(gulp.dest('dist'));
});

Everything works as intended, except the map files also get '.min' appended to them. How do I restrict the renaming to only occur in the dist folder?

Tim
  • 881
  • 8
  • 19
  • add this `'!src/*.map'` to `src` => gulp.src('src/*.js','!src/*.map') – matio Sep 04 '18 at 23:09
  • @matio, the 'src', 'dist', and 'maps' folders are all at the root level. The JS files from 'src' are being extracted into a 'dist' folder properly and the maps folder is being created and the maps file are added. There are no .map files in the 'src' folder for me to exclude. – Tim Sep 04 '18 at 23:22

2 Answers2

1

I did a little more digging and found a solution to this. I ended up breaking the single task into two different ones. Once the files are in the dist folder then I call the 'rename' task. I also used 'vinyl-paths' and 'del' to delete the renamed files. Here is what I have:

var gulp = require('gulp');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var del = require('del');
var vinylPaths = require('vinyl-paths');

gulp.task('compress', ['uglify','rename']);

gulp.task('uglify', function() {
    return gulp.src('src/*.js')
    .pipe(sourcemaps.init())
    .pipe(uglify())
    .pipe(sourcemaps.write('../maps'))
    .pipe(gulp.dest('dist'));
});

gulp.task('rename', ['uglify'], function() {
    return gulp.src('dist/*.js')
    .pipe(vinylPaths(del))
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('dist'));
});
Tim
  • 881
  • 8
  • 19
0

It is possible to combine the two into a single task by leveraging gulp-rename's ability to take a function as input:

gulp.task('prod', function() {
    return gulp.src('src.js'))
        .pipe(sourcemaps.init())
        .pipe(uglify())
        .pipe(sourcemaps.write('.'))
        .pipe(rename(function(path) {
            if (!path.extname.endsWith('.map')) {
                path.basename += '.min';
                //gulp-rename with function only concats 'dirname + basename + extname'
            }
        }))
        .pipe(gulp.dest('build/_asset/js'));
});

The function basically "only" appends the .min suffix if the file extension name is not .map. The output will be src.min.js and src.js.map.

yongtw123
  • 371
  • 8
  • 19