Browserify and Gulp

Using yo gulp-webapp


EDIT: Gulp-browserify has been blacklisted. It’s recommended you use Browserify as a standalone module.

I was recently playing around with Browserify & Gulp. To quickly setup the project i used the gulp-webapp Yeoman generator: https://github.com/yeoman/generator-gulp-webapp

The project scaffold worked beautifully but it didn’t provide a javascript dependency management library. Because i grew tired of the Require.js configuration, i decided to look into Browserify (and it was worth the hours spent debugging).

Here’s what you need to get Browserify & Gulp working in the gulp-webapp generated project.

First, let’s generate the project & install the script:

// bash
yo gulp-webapp
...
npm install --save browserify gulp-browserify reactify

The gulp-load-plugins plugin automatically loads it in our gulpfile.

// gulpfile.js
var $ = require(‘gulp-load-plugins’)();

Now let’s start making use of it. Only use your app’s entry file as the source app/scripts/main.js and set the destination to the .tmp folder.

// gulpfile.js
gulp.task(‘scripts’, function () {
return gulp.src(‘app/scripts/main.js’)
.pipe($.jshint())
.pipe($.jshint.reporter(require(‘jshint-stylish’)))
.pipe($.size())
.pipe($.browserify({
insertGlobals : false,
debug : !gulp.env.production,
transform: ['reactify'] // handles jsx
}))
.pipe(gulp.dest(‘./.tmp/scripts/’));

});

Next, change the folder order in the connect task. This will assure both your development and production builds use the “browserified” ./tmp/scripts/main.js file:

// gulpfile.js
gulp.task(‘connect’, function () {
var connect = require(‘connect’);
var app = connect()
.use(require(‘connect-livereload’)({ port: 35729 }))
.use(connect.static(‘.tmp’))
.use(connect.static(‘app’))

.use(connect.directory(‘app’));

Lastly, watch the new js file for changes:

// gulpfile.js
 gulp.watch([
‘app/*.html’,
‘.tmp/styles/**/*.css’,
‘.tmp/scripts/**/*.js’,
‘app/images/**/*’
]).on(‘change’, function (file) {
server.changed(file.path);
});

You can now take it for a test drive. Both gulp serve & gulp build will use the main.js file generated by Browserify.

Email me when Andrei Rosca publishes or recommends stories