Search code examples
jquerygulpbrowserify

Can't find jquery when using Browserify and separating common libs


I have inherited a large Gulpfile in an Express app which has two steps I'm working with:

build-common-lib - Combines and minifies common libraries such as jQuery and underscore into "common.min.js"

build - Browserifies js files in a "js/modules/*.js" glob, excluding any modules in the "build-common-lib" step, e.g. "contact.js"

At this point all contact.js contains before browserification is:

var $ = require('jquery');

I'm including common.min.js right before the closing body tag, followed by contact.min.js. The problem I'm running into is:

Uncaught Error: Cannot find module 'jquery'

If I Browserify contact.js on its own:

browserify -e contact.js -o contact.min.js

the problem is resolved, but completely defeats the purpose of separating the common libs.

How can I properly reference jQuery in contact.js?

The Gulpfile is quite large, so I've omitted it here. I'm not receiving any errors when running the tasks, but please let me know if you need to see any portions.


Solution

  • I think that the problem you are facing is that browserify will wrap each file on the bundle into its own IIFE (Immediately-invoked function expression), thus, this var $ = require('jquery'); will only have validity on its own context (the IIFE resulting inside build-common-lib IIFE).

    To workaround this, add jQuery explicitly to the window object, so other IIFE can have access to it.

    Try something like this (depending also on the alias you want to use):

    window.$ = window.jQuery = require( 'jquery' );