NodeJS: Static imports possible?

2.9k Views Asked by At

Question in short:

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

Example of what I'd like to do:

I have a file m1.js which contains functions:

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

Then I have a file app.js which imports m1.js:

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

Now, what I'd like to do is to import the functions of m1.js such 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 the file m1.js:

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

and tried to import m1.js in app.js as follows but it wasn't able to find add(x,y):

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

There are 1 best solutions below

1
On BEST ANSWER

You were close with your attempt. The one small change you have to make is replace this with global when static is called:

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. That means that in browsers if you're in the global scope var something will define a global variable. In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.