NodeJS: static import possible?

Shortly speaking:

Is there a way to statically import the functions of another JS file into NodeJS? (How is Java static-import?)

An example of what I would like to do:

I have a file m1.js

that contains functions:

function add(x,y) { return x + y }
exports.add = add

      

Then I have a file app.js

that imports m1.js

:

m1 = require('./m1')
var result = m1.add(3,4)

      

Now I would like to import the functions m1.js

so that I can call them, without having to prefix the calls with m1.*

:

m1 = require('./m1')
var result = add(3,4)  // instead of m1.add(3,4)

      

What I've tried so far:

I've tried the following, in a file m1.js

:

function add(x,y) { return x + y }
exports.static = function(scope) { scope.add = add }

      

and tried to import m1.js

in the app.js

following, but it couldn't find add(x,y)

:

require('./m1').static(this)
var result = add(3,4)

      

+3


source to share


1 answer


You were close to your attempt. The only small change you have to make is to replace this

with global

when called static

:

require('./m1').static(global)
var result = add(3,4)

      



From the documentation :

global

  • {Object} The global namespace object.

In browsers, the top-level scope is the global scope. This means that in browsers, if you are in the global scope var something

, define a global variable. In Node, this is different. The top-level scope is not a global scope; var something

inside a module, Node will be local to that module.

+4


source







All Articles