The synchronous form of require throws errors when resolving a circular dependency, unless I rename require

StackOverflow https://stackoverflow.com/questions/23271218

Question

I have a strange behaviour in require, that I dont know how to avoid (or maybe I have my basics wrong?).

Consider the following code:

define (require) ->

  potoo = require "potoo"
  service = require "communication.data"

  downloadIfNeeded = ->
    # ...
    service.download()

  new potoo.App
    pageContainer: potoo.UI.NGStylePage
    userRequired:  true
    stdRoute:      "overview"
    onLogin:       downloadIfNeeded

This is not going to work, because 'communication.data' itself requires 'app' (the code shown). so we obviously have a circular dependency. That fails with a 'Uncaught Error: Module name "app" has not been loaded yet for context: _'

Since the downloadIfNeeded function doesn't get called until after the user actually clicks something, I figured, that something like the following should work:

define (require) ->

  potoo = require "potoo"

  downloadIfNeeded = ->
    service = require "communication.data"
    service.download()

  ...

But that actually throws the same error as above. To make it work, i have to use a little hack. I alias the require function with some other name:

define (require) ->

  potoo = require "potoo"
  reqs = require

  downloadIfNeeded = ->
    service = reqs "communication.data"
    service.download()

  ...

Is this the best way to do so? Or would you recommend the CommonJS Style (module.export) that is also supported by requirejs.

Était-ce utile?

La solution

I've done a test here and was able to find a solution. What you have is equivalent to this JavaScript:

define(function (require) {

This is enough to be able to use the (fake) synchronous form of require. However, RequireJS will give you the error you got when you try to use a synchronous require and you have circular dependencies. What you need is this:

define(function (require, exports, module) {

This is so that your module uses exports to export its values and consequently RequireJS has an object that can be updated when the module has finished initialized.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top