5

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.

Community
  • 1
  • 1
azz
  • 5,852
  • 3
  • 30
  • 58

1 Answers1

6

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);
Community
  • 1
  • 1
azz
  • 5,852
  • 3
  • 30
  • 58
  • On the command line (or npm run script) this would be: `browserify -t [ browserify-shim --global ] index.js` (requires the `"browserify-shim": { ... }` entry in package.json). – smhg Feb 08 '16 at 17:50
  • @azz @smhg Thanks for this. Do you know where the `--global` flag is documented? This worked for me but I can't find it in the docs [here](https://www.npmjs.com/package/browserify) or [here](https://www.npmjs.com/package/browserify-shim). – Tim Malone Oct 11 '17 at 01:42