3

I am trying to use RequireJS to use the require() function in the browser. For context, I am trying to work with the Node wrapper for the Lob API: https://github.com/hisankaran/lob-node.

Here's the relevant code:

define (function (require) {
        var LOB = require('lob');
        LOB = new LOB(API_KEY);
    })
    // var LOB = new (require('lob')) (API_KEY);
    console.log('Success?')

It runs successfully, but when I try to actually call anything, for example LOB.bankaccounts.create, it says LOB is not defined.

The Lob docs suggested that I do simply this:

var LOB = new (require('lob')) (LOB_API_KEY);

but I kept getting that the module had not yet been loaded for context error described here (http://requirejs.org/docs/errors.html#notloaded), so I tried the above syntax from the RequireJS website.

I'm super new to RequireJS (and coding in general), so I may just be doing something silly.

Alex Schiff
  • 101
  • 1
  • 7
  • If you are using chrome, have a look in the network tab in dev tools. Are all files requested and delivered as expected, or do you get some 404s or no requests at all? – pax162 Nov 02 '13 at 15:45

1 Answers1

3

The define() function has to actually return the object it defines.

Furthermore, in the browser require() should be used asynchronously as the synchronous call only works, when the module has already been loaded.

That being said, I would restructure your code as follows:

define( ['lob'], function( LOB ){
  return new LOB( API_KEY );
});

Put that in some module definition and load it in your main module, e.g., like this

require( [ 'myLob' ], function( myLob ){
 // do something with myLob
});
Sirko
  • 72,589
  • 19
  • 149
  • 183