Search code examples
javascriptnode.jsimportinclude

Include files in node.js directly


I know this questions sounds like a duplicate of this question but it isn't. This questions shows how to include a file that then stores all of its members in an own namespace. But is there a way to include the file, so that the members are in the default namespace?

So I want something like this,

include("abc.js");

testFunc(1, 2, 3);

where testFunc is declared in abc.js


Solution

  • There is a common namespace in node.js that all loaded files has access to, global

    In abc.js:

    global.testFunc = () => 'bar';
    

    so below will work

    require('./abc');
    
    testFunc(1, 2, 3);
    

    However this is not really advised to be used for performance purposes, except for config values for example