目前我正在这样做:
foo.js
const FOO = 5;
module.exports = {
FOO: FOO
};
并在 bar.js
中使用它:
var foo = require('foo');
foo.FOO; // 5
有没有更好的方法来做到这一点?在导出对象中声明常量感觉很尴尬。
最佳答案
在我看来,使用 Object.freeze
允许 DRYer 和更具声明性的样式。我的首选模式是:
./lib/constants.js
module.exports = Object.freeze({
MY_CONSTANT: 'some value',
ANOTHER_CONSTANT: 'another value'
});
./lib/some-module.js
var constants = require('./constants');
console.log(constants.MY_CONSTANT); // 'some value'
constants.MY_CONSTANT = 'some other value';
console.log(constants.MY_CONSTANT); // 'some value'
过时的性能警告
以下问题已在 2014 年 1 月的 v8 中修复,并且不再与大多数开发人员相关:
请注意,将 writable 设置为 false 和使用 Object.freeze 在 v8 - https://bugs.chromium.org/p/v8/issues/detail?id=1858 中都会产生巨大的性能损失。和 https://jsben.ch/AhAVa
关于javascript - 你如何在 NodeJS 模块中共享常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8595509/