Gulp + browserify + 6to5 + source maps

Stefan Bruvik picture Stefan Bruvik · Jan 22, 2015 · Viewed 10k times · Source

I'm trying to write a gulp task allowing me to use modules in JS (CommonJS is fine), using browserify + 6to5. I also want source mapping to work.

So: 1. I write modules using ES6 syntax. 2. 6to5 transpiles these modules into CommonJS (or other) syntax. 3. Browserify bundles the modules. 4. Source maps refers back to the original ES6 files.

How to write such a task?

Edit: Here's what I have so far:

gulp task

gulp.task('browserify', function() {
    var source = require('vinyl-source-stream');
    var browserify = require('browserify');
    var to5ify = require('6to5ify');

    browserify({
        debug: true
    })
    .transform(to5ify)
    .require('./app/webroot/js/modules/main.js', {
        entry: true
    })
    .bundle()
    .on('error', function(err) {
        console.log('Error: ' + err.message);
    })
    .pipe(source('bundle.js'))
    .pipe(gulp.dest(destJs));
});

modules/A.js

function foo() {
    console.log('Hello World');

    let x = 10;

    console.log('x is', x);
}

export {
    foo
};

modules/B.js

import {
    foo
}
from './A';

function bar() {
    foo();
}

export {
    bar
};

modules/main.js

import {
    bar
}
from './B';

bar();

The code seems to be working, but it's not minified and the source map is inline (which is not really working for production).

Answer

chico picture chico · Jan 22, 2015

Use this as your start point:

var gulp = require('gulp');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var to5ify = require('6to5ify');
var uglify = require('gulp-uglify');

gulp.task('default', function() {
  browserify('./src/index.js', { debug: true })
    .transform(to5ify)
    .bundle()
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
    .pipe(uglify())
    .pipe(sourcemaps.write('./')) // writes .map file
    .pipe(gulp.dest('./build'));
});