gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:12:18 26 4
gpt4 key购买 nike

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

app.js

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

如何从 config.js 访问该硬件变量?配置.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);

关于javascript - 如何从 Node.js 主模块访问全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49502350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com