简体   繁体   中英

NodeJS: can you pass a variable to 'require'?

EDIT: to be clear, the code below has been simplified to focus on the problem at hand. I do know that window does not "exist" in Node. This code is in fact used with jsdom for offline rendering (and as such window IS available in my context).

I need to require a module that must have access to two variables to load: window and document . I am new to Node and I am probably missing something regarding variables' scope. I thought an inner function had access to the outer function's parameters. So here is the mechanism I used (I know this code does not make much sense like this, but I tried to extract the "idea" from actual code):

var t = function(window, document){
  var Chart = require('chart.js');
}

var t2 = function(){
  var window = {};
  var document = {};
  t(window, document);
}

t2();

But it does not work. window and document are undefined when chart.js loads. I need to declare window and document as globals to make it work:

window = null;
document = null;

var t = function(window, document){
  var Chart = require('chart.js');
}

var t2 = function(){
  t(window, document);
}

t2();

But it's probably bad.

How is this done "properly"? Please note I can't modify the chart.js module itself.

can you pass a variable to 'require'?

No.

I am new to Node and I am probably missing something regarding variables' scope. I thought an inner function had access to the outer function's parameters.

 var t = function(window, document){ var Chart = require('chart.js'); } var t2 = function(){ var window = {}; var document = {}; t(window, document); } t2(); 

It does, but the code you're bringing in via require isn't in the t or t2 function above.

While you could create global window and document properties before doing the require :

global.window = /*...*/;
global.document = /*...*/;

...that would be a Bad Thing™ on two levels:

  1. Your require call isn't necessarily the one that loads the chart.js module.

  2. Globals are, you know, icky. That's the technical term.

Instead , have chart.js expose an initialization function. Then you get that, call it with the required dependencies, and you're all set.


Note: NodeJS has no UI. If you're trying to do some kind of offline rendering, you may need a full headless browser like PhantomJS or similar, rather than NodeJS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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