Skip to content

Instantly share code, notes, and snippets.

@rebolyte
Last active January 20, 2017 10:27
Show Gist options
  • Save rebolyte/b41be8895ed0d780faf7 to your computer and use it in GitHub Desktop.
Save rebolyte/b41be8895ed0d780faf7 to your computer and use it in GitHub Desktop.
gulp+browserify+ES6
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var watchify = require('watchify');
var babel = require('babelify');
var uglify = require('gulp-uglify');
var gulpif = require('gulp-if');
var stylus = require('gulp-stylus');
var htmlmin = require('gulp-htmlmin');
var browserSync = require('browser-sync').create();
// https://gist.github.com/danharper/3ca2273125f500429945
// https://github.com/gulpjs/gulp/blob/master/docs/recipes/browserify-transforms.md
// https://egghead.io/lessons/javascript-gulp-and-browserify-adding-live-reload-with-browsersync
var JS_INDEX = './src/js/index.js';
function bundle (bundler, min) {
return bundler
.bundle()
.on('error', function () {
console.error(err);
this.emit('end');
})
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(gulpif(min, uglify()))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./dist/js'))
.pipe(browserSync.stream());
}
function styles (min) {
return gulp.src('./src/style/*.styl')
.pipe(gulpif(min, stylus({compress: true}), stylus()))
.pipe(gulp.dest('./dist/style'));
}
gulp.task('watch-js', function () {
var watcher = watchify(browserify(JS_INDEX).transform(babel), watchify.args);
bundle(watcher);
watcher.on('update', function () {
bundle(watcher);
});
watcher.on('log', function (msg) {
console.log(msg);
});
browserSync.init({
server: './dist',
logFileChanges: false
});
});
gulp.task('js', function () {
return bundle(browserify(JS_INDEX, { debug: true }).transform(babel), false);
});
gulp.task('js:production', function () {
return bundle(browserify(JS_INDEX, { debug: true }).transform(babel), true);
});
gulp.task('html', function () {
gulp.src('src/**/*.html')
.pipe(gulp.dest('./dist'));
});
gulp.task('watch-html', function () {
gulp.watch('src/*.html', ['html']);
});
gulp.task('html:production', function() {
return gulp.src('src/*.html')
.pipe(htmlmin({collapseWhitespace: true, removeComments: true}))
.pipe(gulp.dest('dist'));
});
gulp.task('styles', function () {
return styles(false);
});
gulp.task('watch-styles', function () {
gulp.watch('src/styles/*.styl', ['styles']);
});
gulp.task('styles:production', function () {
return styles(true);
});
gulp.task('default', ['js', 'html', 'styles']);
gulp.task('watch', ['watch-html', 'watch-js', 'watch-styles']);
gulp.task('build:production', ['js:production', 'html:production', 'styles:production']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment