简体   繁体   中英

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

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

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM