Arian
Arian

Reputation: 7749

Dynamic require in Nodejs

I'm requiring a library in NodeJS which has a self-invoking function, that results an error because it looks for an object which is not initialized at that moment .

I want to dynamically require this library when that object is initialized.

Is there any way to dynamically require/ load a library ?

This is the part of library required : https://github.com/sakren/node-google-maps/blob/develop/lib/Google.js#L5

Actually I want to require when the window object is present (client-side rendering).

So something like this :

'use strict';

var React = require('react');
var Map = require('./map.jsx');
var Common = require('../common/common');
var MapStatic = require('./map-static.jsx');

exports.type = function() {
    return 'map';
};

exports.jsx = function(data) {
    if (Common.isServerSide()) {
        return (<MapStatic data={data}/>);
    } else {
        return (
            <Map data={data}/>
        );
    }
};

exports.transform = require('./map-transform.js');

The reason the code looks weired is that I'm using react.

Upvotes: 2

Views: 8068

Answers (2)

user4466350
user4466350

Reputation:

In nodeJS require can be used anywhere at anytime whithout much limitations AFAIK.

Which error is thrown once you require at runtime ? In your else branch.

Upvotes: 3

ben jarman
ben jarman

Reputation: 1138

Try the following.

requires = {}
function getter(key) {
  if(!requires[key]){
    requires[key] = require(key)
  }
  return requires[key]
}

Upvotes: 2

Related Questions