Using Webpack with Gulp

Webpack is an awesome tool for building and bundling your web assets, and I've used it in all of my web projects for a couple of years now. Although it's possible to use just Webpack and nothing else for your client-side builds, I've found that using it with a task runner like Gulp gives you the most flexibility and helps to keep your build pipeline as simple as possible.

Why use Webpack with Gulp?

In larger web projects, in addition to compilation and bundling, you may need to:

  • Start a web server and restart it when your server-side code changes
  • Run unit tests
  • Copy and transform static assets that aren't part of your bundle
  • Do any number of other things I can't think of right now

… and often in a very specific order, too.

Although it's possible to do things like that in Webpack using plugins, I've found that it's easier and cleaner to do them with Gulp instead. Webpack is an asset bundler and that's all it aspires to be; when you do lots of non-bundling build steps with plugins you're doing something it wasn't designed to do and it really shows.

Running Webpack from a Gulp task

You don't need any extra packages to run Webpack from Gulp. Just require Webpack and your webpack.config.js into your gulpfile and invoke it from a Gulp task:

const webpack = require('webpack'),
  webpackConfig = require('webpack.config.js');

gulp.task('js-build', (done) => {
  webpack(webpackConfig, done);
});

I usually set up Webpack to output the bundles to a temporary folder, and then source them from there in a Gulp task to further transform them or just copy them to my site's dist/public folder. For example, in my blog's gulpfile I bundle my JavaScript with Webpack and then minify it separately:

gulp.task('js-minify', () => {
  // gulp.src webpack bundles from the temp folder they were output to
  return gulp.src(dirs.tmp + '/js/*.js')
    .pipe(minifyJs({
      ext: {
        src: '.debug.js',
        min: '.min.js'
      }
    }))
    .pipe(gulp.dest(dirs.dist + '/js'));
});

Doing things this way, I can now manage every development-related task, from rebuilding client-side assets to restarting my Node server, in one place with a very high degree of control & flexibility.