Skip to content

Instantly share code, notes, and snippets.

@jez jez/gulpfile.js
Last active Apr 27, 2016

Embed
What would you like to do?
Handy gulpfile that I use for most of my frontend apps.
/*
* Compiles a Node.js project that uses JavaScript and React
*
* - generates a main.js file in JS_DIR by calling browserify on app.jsx in
* SRC_DIR
*
* Usage:
*
* - gulp
* -> gulp scripts
* - gulp clean
* -> rm -rf $CSS_DIR $JS_DIR
*
* - gulp watch
* - gulp watchify
* - starts watchers for JavaScript
*/
var _ = require('lodash');
var buffer = require('vinyl-buffer');
var del = require('del');
var gulp = require('gulp');
var gutil = require('gulp-util');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var watchify = require('watchify');
// input JavaScirpt folder
var SRC_DIR = './public/src';
// output JavaScirpt folder
var JS_DIR = './public/javascripts';
gulp.task('clean', function(cb) {
return del([JS_DIR], cb);
});
var scripts = function(devMode) {
var config = {};
if (devMode) {
_.extend(config, watchify.args);
}
_.extend(config, { debug: devMode });
// Initialize browserify
// (it does it's own stream things when you call b.bundle())
var b = browserify(SRC_DIR + "/app.jsx", config);
if (devMode) {
b = watchify(b);
b.on('log', gutil.log.bind(gutil, 'watchify log'));
}
// This is where the real heavy lifting is done. In devMode, this will get
// called by watchify on every update. Otherwise, it's called just once (as
// the return of calling scripts(false) ).
var compile = function() {
var result;
result = b.bundle()
.on('error', gutil.log.bind(gutil, 'browserify error'))
// "call my the actual file of my bundle ..."
.pipe(source('main.js'))
// uglify and sourcemaps need a buffer, not a stream
.pipe(buffer());
if (devMode) {
result = result.pipe(sourcemaps.init({
loadMaps: true
})).pipe(sourcemaps.write({
sourceRoot: '/src'
}));
} else {
result = result
.pipe(uglify())
.on('error', gutil.log.bind(gutil, 'uglify error'));
}
// "write my bundle to this directory"
return result.pipe(gulp.dest(JS_DIR));
};
if (devMode) {
// Recompile on changes for watchify
b.on('update', compile);
}
return compile();
};
gulp.task('scripts', function() {
return scripts(false);
});
gulp.task('watchify', function() {
return scripts(true);
});
gulp.task('watch', ['watchify'], function() {});
gulp.task('default', function() {
gulp.start('scripts');
return null;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.