How do you share constants in NodeJS modules?

前端 未结 13 1436
庸人自扰
庸人自扰 2020-12-12 08:56

Currently I\'m doing this:

foo.js

const FOO = 5;

module.exports = {
    FOO: FOO
};

And using it in bar.js:<

13条回答
  •  自闭症患者
    2020-12-12 09:18

    In my opinion, utilizing Object.freeze allows for a DRYer and more declarative style. My preferred pattern is:

    ./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'
    

    Outdated Performance Warning

    The following issue was fixed in v8 in Jan 2014 and is no longer relevant to most developers:

    Be aware that both setting writable to false and using Object.freeze have a massive performance penalty in v8 - https://bugs.chromium.org/p/v8/issues/detail?id=1858 and http://jsperf.com/performance-frozen-object

提交回复
热议问题