我有一个NodeJS应用程序,它在客户机和服务器之间有共同的常量。
常量存储在变量中,而不是内联的。这些变量可以在两个单独的文件中定义,一个用于客户机,另一个用于服务器。
文件1:
// client_constants.js
MESSAGE_TYPE_A = "a";
MESSAGE_TYPE_B = "b";文件2:
// server_constants.js
exports.MESSAGE_TYPE_A = "a";
exports.MESSAGE_TYPE_B = "b";为了避免重复的代码,我想将常量存储在单个位置和客户机和服务器的单一格式中。干吗?
发布于 2012-07-24 21:06:32
你可以这样做:
// constants.js
root = exports ? window
root.MESSAGE_TYPE_A = "a";
root.MESSAGE_TYPE_B = "b";客户端不存在“导出”,在这种情况下,它将使用默认的“窗口”对象。
发布于 2021-07-15 00:37:09
有点像赫克托的答案,但在我的Node版本和我的浏览器中都有效,因为它使用了与"undefined"和typeof的比较。
var context = (typeof exports != "undefined") ? exports : window;
context.constant_name = "constant_name_string";https://stackoverflow.com/questions/11638706
复制相似问题