繁体   English   中英

如何从主要的Node.js模块访问全局变量?

[英]How to access global variable from main Node.js module?

我有简单的app.js,其中包含简单的变量,例如:

app.js

const HW = "Hello, world!";
var config = require('./config');

如何从config.js访问该HW变量? config.js

console.log(HW);

app.js中的导出是否真的将其设置为在config.js中可见?

为了查看在另一个js文件中声明的变量,您必须将其导出到该文件中,然后在需要对该变量的引用的文件中导入/获取它。 因此,如果在app.js中有一个名为HW的const变量,则必须将其导出:

app.js

const HW = "Hello, world!";
module.exports.HW = HW;

然后将其导入您的其他文件中:

config.js

var HW = require("app.js").HW;
console.log(HW);

暂无
暂无

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

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