cnp cnp - 1 year ago 118
Node.js Question

Simple solution to share modules loaded via NPM across multiple Browserify or Webpack bundles

Pulling my hair out here looking for a simple solution to share code, required via NPM, across multiple Browserify or Webpack bundles. Thinking, is there such a thing as a file "bridge"?

This isn't due to compile time (I'm aware of watchify) but rather the desire to extract out all of my vendor specific libs into

so to keep my
filesize down and to not crash the browser with massive sourcemaps. Plus, I find it way cleaner should the need to view the compiled js arise. And so:

// vendor.js


Its very important that the code be loaded from NPM as opposed to Bower, or saved into some 'vendor' directory in order to be imported via a relative path and identified via a shim. I'd like to keep every library reference pulled via NPM except for my actual application source.

I keep all of my sourcecode, and via the
array, exclude vendor libraries listed above from compilation:

// app.js

var React = require('react');
var _ = require('lodash');

var Component = React.createClass()

// ...

And then in
, I require both files

// index.html
<script src='vendor.js'></script>
<script src='app.js'></script>

Using Browserify or Webpack, how can I make it so that
can "see" into those module loaded via npm? I'm aware of creating a bundle with externals and then referencing the direct file (in, say,
) via an alias, but I'm hoping to find a solution that is more automatic and less "Require.js" like.

Basically, I'm wondering if it is possible to bridge the two so that
can look inside
in order to resolve dependencies. This seems like a simple, straightforward operation but I can't seem to find an answer anywhere on this wide, wide web.


Answer Source

With webpack you'd use multiple entry points and the CommonChunkPlugin.

Taken from the webpack docs:

To split your app into 2 files, say app.js and vendor.js, you can require the vendor files in vendor.js. Then pass this name to the CommonChunkPlugin as shown below.

module.exports = {
  entry: {
    app: "./app.js",
    vendor: ["jquery", "underscore", ...],
  output: {
    filename: "bundle.js"
  plugins: [
    new webpack.optimize.CommonsChunkPlugin(
        /* chunkName= */"vendor",
        /* filename= */"vendor.bundle.js"

This will remove all modules in the vendor chunk from the app chunk. The bundle.js will now contain just your app code, without any of it’s dependencies. These are in vendor.bundle.js.

In your HTML page load vendor.bundle.js before bundle.js.

<script src="vendor.bundle.js"></script>
<script src="bundle.js"></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download