40

I'm just getting started with require.js. I have successfully wrapped jquery, some plugins, and a couple of my own modules. I'm trying to interact with my modules (or jquery) from Firebug (or Google Chrome's JS console), and I'm not having much luck.

What is the correct way to access these modules from the console?

Nicolas Kaiser
  • 1,628
  • 2
  • 14
  • 26
erikcw
  • 10,787
  • 15
  • 58
  • 75

2 Answers2

54

Say we have module /app/scripts/methodsModule.js that returns a few methods:

define({
    someMethod: function() {
        // do stuff
    },
    anotherMethod: function() {
        // do some more stuff
    }
});

In our data-main file /app/scripts/main.js we have:

require(['methodsModule'], function(methods) {
    methods.someMethod() // call someMethod
    methods.anotherMethod() // call anotherMethod
})

Once requireJS loads up our data-main, we can access any modules that have already been loaded by requireJS from the javascript console command line like so:

>> methods = require('methodsModule'); // requireJS has module methodsModule stored
>> methods.someMethod() // call someMethod
>> methods.anotherMethod() // call anotherMethod

If a module hasn't been loaded by a call to require() or define(), we have to pass our own callback for the require function to call after the module has been loaded:

>> myCB = function(methods) { methods.someMethod() }
>> require(['methodsModule'], myCB)

Otherwise, requireJS throws an error saying that the module has not yet been loaded..

benastan
  • 2,268
  • 15
  • 14
  • 1
    does this work with requireJS "optimized" scripts? Maybe I am doing something wrong here, but it did not seem to work for me. – Stephen Aug 29 '13 at 07:23
  • Still valid as of 05/20/2015. In converting a "primitive" project to AMD, I needed to ensure that everything was working. However, I couldn't locate where the returned module object was going after define executed. Great explanation. – Umair Ishaq May 20 '15 at 18:13
15

There is a way without using callbacks.

If you module was not required in console or you application before, you can just require it first:

require(['methodsModule']);

after that you can use "dynamic" require to access it:

require('methodsModule').someMethod();
Valentin Nemcev
  • 4,940
  • 2
  • 20
  • 21
  • That was seriously easier than what I was trying, `+0.1E1`. I prefer to just load the module to the window for easy access though. `require([m='lib/imagesloaded']); imagesLoaded=require(m);` – Orwellophile Sep 20 '16 at 02:22