Search code examples
jquerybrowserifyjquery-cookiebrowserify-shim

Fake global jQuery with browserify-shim? (Cannot find module 'jquery')


I'm encountering a puzzling issue with Browserify, regarding jQuery plugins. As I have multiple bundles for separate sub-apps, I have some global libraries as <script> tags in my HTML to prevent repetition.

I'm using gulp, browserify-shim and babelify to create my bundles.

Within package.json:

"dependencies": {
  "jquery.cookie": "^1.4.1",
  ...
},
"browserify-shim": {
  "jquery": "global:jQuery",
   ...
},
"browserify": {
  "transform": [
    "browserify-shim"
  ]
}

Within base.html: (In production these will be CDN links)

<!--[if lt IE 9]><script src="/bower_components/jquery-legacy/jquery.min.js"></script><![endif]-->
<!--[if gte IE 9]><!-->
<script src="/bower_components/jquery/dist/jquery.min.js"></script>
<!--<![endif]-->

In one of my source files:

import $ from 'jquery'; // this works
import 'jquery.cookie'; // this crashes browserify

Error message:

Error: Cannot find module 'jquery' from '/path/to/node_modules/jquery.cookie'

jQuery is not installed with npm as I do not want it rolled into my bundles.

I'm guessing that the issue here is that there is a call require('jquery') within jquery.cookie.js that is not being resolved.

How do I 'fake' the existence of a global jQuery instance to a plugin with browserify-shim?


NB: This solution does not meet my needs, as jQuery will be rolled into many bundles.


Solution

  • Solved. This solution seems to work perfectly.

    For reference, here is my (fixed) watchify call from my Gulpfile:

    var b = browserify({
        entries: [app.input_dir + app.entry],
        debug: true,
        cache: {},
        packageCache: {},
        fullPaths: true
    })
        .transform(babelify)
        .transform({
            global: true
        }, 'browserify-shim')
        .plugin('minifyify', {
            map: app.output_dir + app.entry + '.map',
            output: app.output_dir + app.entry + '.map'
        });
    
    var watcher = watchify(b);