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();
3
  • 1
    You can find the answer here (Please check the third answer): stackoverflow.com/questions/5797852/… Commented Jun 18, 2016 at 15:20
  • you're link is show exactly what i wanted to avoid Commented Jun 18, 2016 at 15:22
  • Yes the third answer is right! sorry, i just checked the 2 first. Thanks! Commented Jun 18, 2016 at 15:34

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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
It would not work, tested that first and the function was not available @Xsmael
This is very weird! now it works for me too, and i don't know why -_-
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.