0

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

user11914177
  • 885
  • 11
  • 33
  • Does this answer your question? [How do I include a JavaScript file in another JavaScript file?](https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file) – fedesc Aug 08 '20 at 08:50
  • Not exactly, but it doesn't matter, since an answer has been found – user11914177 Aug 08 '20 at 08:52

2 Answers2

1

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

Maxime Helen
  • 1,382
  • 7
  • 16
1

First nodejs does not know include, you should use require or import

If you have a module (testModule):

module.exports = {
    testFunc: (...args) => {/* ... */}
}

You should be able to import testFunc into the current 'namespace' using

const {testFunc} = require("./testModule.js");
KooiInc
  • 119,216
  • 31
  • 141
  • 177