Brant
Brant

Reputation: 15334

How do I prevent browserify from including multiple versions of sub-dependencies?

In my front-end code, I use require() to pull in libraries which, in turn, depend on different versions of Underscore.js. As a result, when I use browserify to bundle everything together, the output contains multiple copies of Underscore. Is there a way to tell browserify that require('underscore') should always import a particular file?

As a demonstration of the problem, imagine I have the following dependencies:

// package.json
"dependencies": {
  // Depends on underscore 1.7.0
  "backbone": "^1.1.2",

  // Depends on underscore 1.6.0
  "backbone.marionette": "^2.3.0"
}

In main.js I use both libraries:

// main.js
var Backbone = require('backbone');
var Marionette = require('backbone.marionette');
console.log("Hello, world!");

When I create a bundle, multiple versions of Underscore are included:

PS> browserify main.js -o out.js
PS> findstr _.VERSION out.js
  _.VERSION = '1.7.0';
  _.VERSION = '1.6.0';

(I created a GitHub repository with a more complete example. Clone it and run npm install && npm test to see it in action)

I tried adding a browser section to my package.json like the following, but it didn't seem to have any effect:

// package.json
"browser": {
  "underscore": "./node_modules/underscore/underscore.js"
}

I understand why npm installs duplicate dependencies (and it makes sense to do it this way for server-side code) but what's the correct way to deal with this when using browserify?

Upvotes: 15

Views: 3220

Answers (1)

mantoni
mantoni

Reputation: 1622

There is a duplicate detection in Browserify that should avoid loading the same version more than once. However, if your node_modules tree contains multiple copies of the same module, this detection might (should?) fail.

The solution that I'm using is to dedupe the package structure with npm:

npm dedupe

This will only leave unavoidable dupes in your dependency tree and it will log a warning about those dupes so that you can double check.

Upvotes: 10

Related Questions