[英]Node use variables from another file
I have long list of variables at the beginning of my single file app. 在单个文件应用程序的开头,我有一堆变量。 How can I move variables to another file and use them from there.
如何将变量移动到另一个文件并从那里使用它们。 Can I do that without requiring them as modules?
我可以在不需要它们作为模块的情况下这样做吗?
My code is written like this so I need variables to work just like the would be in the same file. 我的代码是这样写的,所以我需要变量才能像在同一文件中一样工作。
const1 = 'apple'
const2 = 'banana'
const3 = 'pear'
…
let1 = const1
console.log(let1)
and that should output apple. 那应该输出苹果。
And I want move those const variables from top 我想从顶部移动那些const变量
Help would be much appreciated! 帮助将不胜感激!
You have to export the variable in vars.js 您必须在vars.js中导出变量
let const1 = 'apple' exports.const1 = const1;
And then access via: 然后通过以下方式访问:
var request = require(./vars.js); ... let x = request.const1;
Hope it helps! 希望能帮助到你!
It isn't a good practice but you can declare the variables as properties of the global object... 这不是一个好习惯,但是您可以将变量声明为全局对象的属性...
global.const1 = 'apple'
global.const2 = 'banana'
global.const3 = 'pear'
…
let1 = global.const1
console.log(let1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.