Skip to content
This repository has been archived by the owner on Dec 15, 2020. It is now read-only.

Separate app and 3rd party bundles

Caleb Land edited this page Sep 7, 2015 · 1 revision

Here is an example (thanks @ccoenen for the idea) of how you can separate your app bundle (app.js in this example) from your NPM dependencies (npm.js in this example).

The directory structure for this project is:

project/
  app/          # Contains our application code
    index.js
  npm_modules/  # Contains our 3rd party code
  public/       # Contains our HTML, CSS, etc
    index.html
  Brocfile.js
  package.json

And the Brocfile.js:

var browserify = require('broccoli-fast-browserify');
var broccoliSource = require('broccoli-source');
var merge = require('broccoli-merge-trees');
var WatchedDir = broccoliSource.WatchedDir;
var UnwatchedDir = broccoliSource.UnwatchedDir;

var appJs = new WatchedDir('app');
var vendorJs = new UnwatchedDir('node_modules'); // it really doesn't matter what directory this is
                                                 // since we use the require option to load all of 
                                                 // the modules

/*
 * Our application javascript. It has entrypoints, and uses the 'externals'
 * option to specify that we don't want to include the npm modules in this
 * bundle
 */
// Awesome: just put it in package.json, and it's there :)
var packagejson = require('./package.json');
var thirdPartyDependencies = Object.keys(packagejson.dependencies);
appJs = browserify(appJs, {
  browserify: {
    debug: true // Include source maps
  },
  bundles: {
    'app.js': {
      entryPoints: ['index.js'],
      externals: thirdPartyDependencies // <-- these will not be in app.js
    },
  }
});

/*
 * Our third party dependencies go into a separate file. We don't include an
 * entrypoint but instead use Browserify's `require` option to specify which
 * modules we want to 're-export' into our output file so they can be
 * `require()`'d by our 'app.js' bundle
 */
vendorJs = browserify(vendorJs, {
  browserify: {
    debug: false // No source maps for the vendored files
  },
  bundles: {
    'npm.js': {
      entryPoints: [], // no entrypoint
      require: thirdPartyDependencies // <-- instead, re-export our 3rd party modules
    },
  }
});

module.exports = merge(['public', appJs, vendorJs]);

The cool thing about this is that the 3rd party dependencies are picked up from the dependencies section of the package.json file automatically (you need to restart broccoli to pick up new ones…).

Clone this wiki locally