0

I wanted to include some js files without using require because it would link it to a variable, and i have some functions i would like to call directly. how can i do it ? is it bad practice ?

what i want to avoid is this: let's say i have tool.js as follow:

function foo() {
    log.debug("foo");
}    
exports.foo = foo;

in app.js

var tool= require('tools.js');

tool.foo();

i would like to be able to call foo without creating a module for it as if it was define in app.js; like so

foo();
Xsmael
  • 3,624
  • 7
  • 44
  • 60

2 Answers2

2

You can require a file and use its functions without assigning it to a variable by using the global object.

file1.js

function logger(){
    console.log(arguments);
}

global.logger = logger;

file2.js

require('./file1');

logger('ABC');

This approach would get rid of variable scoping and would pollute the global namespace potentially leading to clashes with variable naming.

Gabs00
  • 1,869
  • 1
  • 13
  • 12
  • would this work if `global.logger = logger;` was missing in file1.js ? coz i saw someone doing it in a tutorial but it wasn"t working for me thanks for the warning by the way – Xsmael Jun 18 '16 at 15:31
  • It would not work, tested that first and the function was not available @Xsmael – Gabs00 Jun 18 '16 at 15:33
  • This is very weird! now it works for me too, and i don't know why -_- – Xsmael Jun 18 '16 at 15:52
0

You need to use global like this,

======= app.js ======

global.foo= require('tools.js'); // declare as global
foo(); // can be called from all files
Alongkorn
  • 3,968
  • 1
  • 24
  • 41