简体   繁体   English

NodeJS:静态导入可能吗?

[英]NodeJS: Static imports possible?

Question in short: 问题简而言之:

Is there a way to statically import functions of another JS file in NodeJS? 有没有办法静态导入NodeJS中另一个JS文件的功能? (As the static-import of Java?) (作为Java的静态导入?)

Example of what I'd like to do: 我想做的例子:

I have a file m1.js which contains functions: 我有一个包含函数的文件m1.js

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

Then I have a file app.js which imports m1.js : 然后我有一个文件app.js导入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.js的功能,这样我就可以调用它们,而不必使用m1.*前缀调用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 : 我在文件m1.js尝试了以下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) : 并尝试在app.js导入m1.js ,如下所示,但它无法找到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 this with global when static is called: 你必须做出的一个小的变化是更换thisglobalstatic调用:

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

From the documentation : 文档

global 全球

  • {Object} The global namespace object. {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. 这意味着在浏览器中,如果您在全局范围内, var something会定义一个全局变量。 In Node this is different. 在Node中,这是不同的。 The top-level scope is not the global scope; 顶级范围不是全球范围; var something inside a Node module will be local to that module. Node模块内的var something将是该模块的本地内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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