你如何在NodeJS模块中共享常量? [英] How do you share constants in NodeJS modules?
本文介绍了你如何在NodeJS模块中共享常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前我这样做:
foo.js
const FOO = 5;
module.exports = {
FOO: FOO
};
并在 bar.js
中使用它:
var foo = require('foo');
foo.FOO; // 5
有更好的方法吗?在exports对象中声明常量会感觉很尴尬。
Is there a better way to do this? It feels awkward to declare the constant in the exports object.
推荐答案
您可以使用<$ c将其显式导出到全局范围$ c> global.FOO = 5 。然后你只需要文件,甚至不需要保存你的返回值。
You can explicitly export it to the global scope with global.FOO = 5
. Then you simply need to require the file, and not even save your return value.
但实际上,你不应该这样做。保持正确封装的东西是一件好事。你已经有了正确的想法,所以继续做你正在做的事情。
But really, you shouldn't do that. Keeping things properly encapsulated is a good thing. You have the right idea already, so keep doing what you're doing.
这篇关于你如何在NodeJS模块中共享常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文