Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

browserify

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?

like image 391
Brant Bobby Avatar asked Jan 13 '15 21:01

Brant Bobby


People also ask

Is Browserify a dev dependency?

We can also include browserify itself as a dependency, however it isn't a dependency for the project to run – any user to our app can find Superman without needing to run Browserify. It is one of our devDependencies – modules required for developers to make updates to this app. Now we've got a package.

What does Browserify?

Browserify is an open-source JavaScript bundler tool that allows developers to write and use Node. js-style modules that compile for use in the browser.


1 Answers

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.

like image 199
mantoni Avatar answered Oct 23 '22 12:10

mantoni