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)
You were close with your attempt. The one small change you have to make is replace
thiswithglobalwhenstaticis called:From the documentation: