Using ES2015 with Babel and Browserify

gulpfile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
var watchify = require('watchify'),
browserify = require('browserify'),
gulp = require('gulp'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer'),
gutil = require('gulp-util'),
sourcemaps = require('gulp-sourcemaps'),
assign = require('lodash.assign'),
rename = require('gulp-rename'),
babelify = require('babelify'),
uglify = require('gulp-uglify'),
exit = require('gulp-exit');

// add custom browserify options here
var customOpts = {
entries: ['./src/app.js'],
debug: true,
transform: [babelify]
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts));

gulp.task('js', bundle); // so you can run `gulp js` to build the file
b.on('update', bundle); // on any dep update, runs the bundler
b.on('log', gutil.log); // output build logs to terminal

function bundle() {
return b.bundle()
// log errors if they happen
.on('error', gutil.log.bind(gutil, 'Browserify Error'))
.pipe(source('./src/app.js'))
// optional, remove if you don't need to buffer file contents
.pipe(buffer())
// optional, remove if you dont want sourcemaps
.pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
// Add transformation tasks to the pipeline here.
.pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
.pipe(rename({
dirname: ''
}))
.pipe(sourcemaps.write('./')) // writes .map file
.pipe(gulp.dest('./dist'))
.pipe(gutil.env.type === 'production' ? exit() : gutil.noop());
}
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import * as _ from '../bower_components/lodash/lodash.js';
import $ from '../bower_components/jquery/dist/jquery.js';
import { square, diag } from './lib1';
import { division } from './lib2';


console.log('Square of default (5): ' + square()); // 121
console.log('Divide 8 by 2: ' + division(8, 2)); // 4
console.log('Lodash (5): ' + _.first([5, 2, 3])); // 5

let bodyText = `This is really
now
perfectly
legal.`;


$('body').append(bodyText);
lib1.js
1
2
3
4
5
6
7
8
9
10
11
const sqrt = Math.sqrt;

function square(x = 5) {
return x * x;
}

function diag(x, y) {
return sqrt(square(x) + square(y));
}

export {sqrt, square, diag};
lib2.js
1
2
3
4
5
let division = function(x, y) {
return x / y;
};

export {division};

Resources