Search code examples
gulpbrowserifybabeljsuglifyjs

Having problems with gulp-uglify


I'm having some serious trouble getting gulp-uglify to minify my files.

Here is my gulpfile.

var gulp       = require('gulp');
var gutil      = require('gulp-util');
var browserify = require('browserify');
var babelify   = require('babelify');
var source     = require('vinyl-source-stream');
var buffer     = require('vinyl-buffer');
var uglify     = require('gulp-uglify');
var size       = require('gulp-size');

gulp.task('scripts', function () {

  var bundler = browserify({
    entries: ['views/main.js'],
    debug: true,
  })
  .transform(babelify, { presets: ['react', 'es2015'] });

  bundler.bundle()
      .pipe(source('main.js'))
      .pipe(buffer())
      .pipe(uglify())
      .pipe(gulp.dest('./public/'));
});

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

Using gutil, I found the line giving gulp-uglify the error, which is very confusing:

{ [Error: /Users/fzxt/Documents/Web/Chatr/main.js: Unexpected token: keyword (const)]
  message: '/Users/fzxt/Documents/Web/Chatr/main.js: Unexpected token: keyword (const)',
  fileName: '/Users/fzxt/Documents/Web/Chatr/main.js',
  lineNumber: 66598..

It's having trouble with the keyword const which is odd because I'm transforming the bundler with babelify before I give it to uglify. I've also put the presets as well.

Could anyone help me out on how to deal with this? Thanks.


Solution

  • If you are using vanilla browserify, you will need to do it like this:

    var gulp = require('gulp');
    var browserify = require('browserify');
    var babelify = require('babelify');
    var transform = require('vinyl-transform');
    var uglify = require('gulp-uglify');
    
    gulp.task('browserify', function () {
      var browserified = transform(function(filename) {
        var b = browserify({
          entries: filename,
          debug: true,
          transform: [
            [babelify, {
              presets: ['react', 'es2015']
            }]
          ]
        });
        return b.bundle();
      });
      
      return gulp.src(['views/main.js'])
        .pipe(browserified)
        .pipe(uglify())
        .pipe(gulp.dest('./dist'));
    });