RequireJS module's dependencies not being eval

2019-06-02 20:56发布

问题:

I have the following (extremely simple) module definition, in CoffeeScript:

# backbone/routers/appointments_router.js.coffee
define ["app", "underscore", "backbone"], (App, _, Backbone) ->
  console.log(Backbone)

And here's my config and stuff:

# application.js.coffee
requirejs.config
  paths:
    underscore: "lodash.min"
    backbone: "backbone"
    appointmentsRouter: "backbone/routers/appointments_router"
    "backbone-relational": "backbone-relational"

requirejs ["app", "underscore", "backbone", "appointmentsRouter"], (App, _, Backbone, AppointmentsRouter) ->

Here's what's happening: when I load my page, I get undefined in the console, even though Backbone is listed as a dependency. What's even more puzzling is that if I type Backbone into the console, Backbone is defined.

How could it be that Backbone is ultimately getting evaluated, but my appointments_router.js.coffee doesn't know about Backbone?

回答1:

Underscore or Backbone aren't AMD compliant, so defining the path isn't enough. Luckily Require.js offers the shim -functionality as an answer to this.

So you'll have to add something like this

requirejs.config( // shouldn't this be just require?
  paths: ..., // don't change these
  shim: {
    "underscore": {
      exports: "_" // define the export
    },
    "backbone": {
      deps: ["underscore"], // define dependencies for backbone
      exports: "Backbone"
    }
  }
);

hope this helps!