Dave Mackintosh
Dave Mackintosh

Reputation: 2796

Node JS require without var

{This has nothing to do with Twitter}

Bit of an interesting question, interesting in that its probably stupid and you can laugh but I will have at least an answer to this damn itch.

Currently I use

var Bootstrap = require('library/Bootstrap');
Bootstrap.run();

When what would be really great is if I could do something like this in the Bootstrap index.js

module.exports.Bootstrap = My_Bootstrap;

And call it willy nilly like this

require('library/Bootstrap');
Bootstrap.run();

Without having to declare another variable to my space, is there a way to do this or am I staring at a screen wondering, dreaming, getting lost, coming back and wasting time?

edit So this is what I did in the end:

I created a single global object and am only adding important modules to it so they can be accessed and instantiated. This turned out to be an amazing answer and solution and really handy

Upvotes: 7

Views: 3966

Answers (3)

Forbesmyester
Forbesmyester

Reputation: 936

You cannot do it the way you say, that implies a global, which is almost certainly not what you want.

However what yo can do is this:

require('your_library').call(this,arg1,arg2);

For instance you could be using the node-validator library.

Your are intended to use it like:

sanitize = require('validator').sanitize
var str = sanitize('aaaaaaaaab').ltrim('a');

But you can skip all that and do

var str = require('validator').sanitize('aaaaaaaaab').ltrim('a')

As far as I understand there are no downsides to doing this either in terms of memory/speed.

In your specific case, you are aware you can skip a bit...

File: MyBootStrap.js

Module.exports = MyBootstrap

File: index.js (or other)

require('library/Bootstrap.js')()

Upvotes: 1

Farid Nouri Neshat
Farid Nouri Neshat

Reputation: 30430

Well you can just modify the global object. This is similar to window object on browsers. So you can write a wrapper for your module like the following:

global.Bootstrap = My_Bootstrap

The global object is shared between modules. Then you can just use with Bootstrap wherever you are.

Upvotes: 7

Elliot Bonneville
Elliot Bonneville

Reputation: 53311

Nope, you have to declare the variable. You could get inside the require function, though, and make that do the work for you. I'm not overly familiar with Bootstrap's internal architecture but it seems like something like this should do the trick:

// put this in some out-of-the-way cubbyhole somewhere
var oldRequire = require;
function require(path) {
    Bootstrap = oldRequire(path);
}

// and this would go in your main file
require("library/Bootstrap");
Bootstrap.run();

Upvotes: 1

Related Questions