Search code examples
javascriptjquerynpmbrowserifycommonjs

Browserify: prevent including the same npm-module more then once in the same application


For learning purposes I am working on a small chat application, based on jQuery. I want to make it a CommonJS Module, which I can reuse in other projects, just doing something like:

var Chat = require('chat'),
    mainChat = new Chat({/* ...params... */})

I am also using browserify for bundling all my dependencies. In my "chat.js" file I am doing:

var $ = require('jquery');

it gives me a local jquery object, and I don't have to worry about whether jQuery was included somewhere in the project earlier, or not. But if somewhere in my project, in another "*.js" file I will do the same thing - it will create another local jQuery object and my bundle would become really huge. My question: is there some method or tool to prevent including some npm-module more then once in the same application?


Solution

  • If both versions of jQuery are exactly the same, browserify will detect it in its dedupe step and include it just once.

    See https://github.com/substack/browserify-handbook#dedupe for details.