Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browserify-shim dependency undefined?

I'm trying to break an existing application up into modules. I chose to do this using Browserify, beause of its syntax, which mimics NodeJS requires nicely.

My project depends on a couple of external modules, one of which is Backbone. Therefore, I'm using browserify-shim. However, I'm encountering a problem with it.

In my package.json I have defined the following:

```

  "browserify": {
    "transform": [
      "browserify-shim"
    ]
  },
  "browser": {
    "jQuery": "public/js/vendor/jquery-2.0.3.min.js",
    "lodash": "public/js/vendor/lodash.js",
    "Backbone": "public/js/vendor/backbone-1.1.2.js"
  },
  "browserify-shim": {
    "jQuery": "global:$",
    "lodash": "_",
    "Backbone": {
      "exports": "global:Backbone",
      "depends": [
        "jQuery",
        "lodash"
      ]
    },
    "BackboneLocalStorage": {
      "depends": [
        "Backbone"
      ]
    }
  },

```

In one of my files I require Backbone like this:

var Backbone = require('Backbone');

When compiling my bundle, Browserify doesn't complain, so everything seems fine. However, when loading my application in the browser I receive the error Cannot read property 'Model' of undefined (I'm calling Backbone.Model.extend() there) which doesn't make much sense to me.

When I change "exports": "global:Backbone", to "exports": "Backbone", Browserify stops with the message

Error: module "Backbone" not found

I don't get what I'm doing wrong and I feel the Browserify-shim docs are not much help here. They give a nice example, but don't really explain what's going on or what would cause such an error. Can anyone enlighten me?

like image 356
lunanoko Avatar asked Feb 22 '26 09:02

lunanoko


1 Answers

I believe you are using Browserify-shim 3.0 since you have the config in your package.json (please correct me if I'm wrong). Based on the docs for 3.0, exposing a global config seems to indicate to the shim that you have included the library from outside the bundle; in the example case, three.js is included from a CDN.

Try removing global: so it reads:

"Backbone": {
  "exports": "Backbone",
  "depends": [
    "jQuery",
    "lodash"
  ]
},

Or perhaps drop the whole exports part. another challenge with Backbone is to make sure you have exposed Backbone's $ property properly.

I've been playing with this myself, and I would agree the docs are... confusing at best. In my case, I simply npm install both Backbone and jQuery with --save and require those two without a shim (my plugins etc and jQuery are now shimmed, but not Backbone itself).

Hope this helps!

like image 181
zedd45 Avatar answered Feb 24 '26 23:02

zedd45