Skip to content

Instantly share code, notes, and snippets.

@ryanseddon
Created January 5, 2014 00:08
Show Gist options
  • Select an option

  • Save ryanseddon/8262519 to your computer and use it in GitHub Desktop.

Select an option

Save ryanseddon/8262519 to your computer and use it in GitHub Desktop.
Gulp + browserify conundrum. How can I get browserify to properly transform the es6 module syntax to CommonJS syntax and pass along the stream so browserify can figure out how to bundle up the file into a single dist release? Is this possible?
var gulp = require('gulp');
var es6ModuleTranspiler = require('gulp-es6-module-transpiler');
var browserify = require('gulp-browserify');
var through = require('through');
function transpileModuleSyntax(file) {
var data = '';
return through(write, end);
function write (buf) { data += buf }
function end () {
this.queue(es6ModuleTranspiler({type: 'cjs'}));
this.queue(null);
}
}
gulp.task('build', function() {
// Transpile ES6 modules
// browser friendly
gulp.src('src/*.js')
.pipe(browserify({
transform: [transpileModuleSyntax],
debug: true
}))
.pipe(gulp.dest('./dist'));
});
// This is the entry point that browserify should figure out
// ES6 module syntax that the transform method should take care of
import { support, dispatchClick } from 'utils';
if(support) {
dispatchClick();
}
var support = (function support() {
return true;
}());
function dispatchClick(coords){
// Create synthetic click event
}
export { support, dispatchClick };
@narqo
Copy link

narqo commented Jan 7, 2014

As far as I understand, there are a couple of problems in your solution:

  1. es6ModuleTranspiler() returns through stream which reads/writes with vinyl File object, while browserify's transform should return a stream that takes the raw file contents.

  2. with gulp.src('src/*.js').pipe(browserify(...)) you are trying to transform all js-files in src directory. But browserify will automatically process there requires, inserting it's content. So your final bundle will consist a lot of duplicate code.

You should pipe only single entry point of your app.

This works for me:

var gulp = require('gulp'),
    browserify = require('gulp-browserify'),
    through = require('through'),
    Compiler = require('es6-module-transpiler').Compiler;

function compile(opts) {
    var buf = '';
    return function () {
        return through(write, end);
    };

    function write(data) {
        buf += data;
    }

    function end() {
        this.queue((new Compiler(buf, '', opts)).toCJS());
        this.queue(null);
    }
}

gulp.task('build', function() {
    gulp.src('src/main.js')
        .pipe(browserify({
            transform : [compile()],
            debug : true
        }))
        .pipe(gulp.dest('./dist'));
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment