简体   繁体   English

如何在浏览器中使用require

[英]How to use require in the browser

I am trying to use RequireJS to use the require() function in the browser. 我正在尝试使用RequireJS在浏览器中使用require()函数。 For context, I am trying to work with the Node wrapper for the Lob API: https://github.com/hisankaran/lob-node . 对于上下文,我正在尝试使用Lob API的Node包装器: 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. 它成功运行,但是当我尝试实际调用任何东西时,例如LOB.bankaccounts.create,它表示LOB未定义。

The Lob docs suggested that I do simply this: Lob文档建议我这样做:

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. 但我一直认为该模块尚未加载此处描述的上下文错误( http://requirejs.org/docs/errors.html#notloaded ),所以我尝试了RequireJS网站上面的语法。

I'm super new to RequireJS (and coding in general), so I may just be doing something silly. 我是RequireJS的新手(并且编码一般),所以我可能只是在做一些愚蠢的事情。

The define() function has to actually return the object it defines. define()函数必须实际返回它定义的对象。

Furthermore, in the browser require() should be used asynchronously as the synchronous call only works, when the module has already been loaded. 此外,在浏览器中, require()应该异步使用,因为只有在已经加载模块时,同步调用才有效。

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, eg, like this 将它放在一些模块定义中并将其加载到主模块中,例如,像这样

require( [ 'myLob' ], function( myLob ){
 // do something with myLob
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM