How do you share constants in NodeJS modules?

前端 未结 13 1454
庸人自扰
庸人自扰 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:16

    As an alternative, you can group your "constant" values in a local object, and export a function that returns a shallow clone of this object.

    var constants = { FOO: "foo" }
    
    module.exports = function() {
      return Object.assign({}, constants)
    }
    

    Then it doesn't matter if someone re-assigns FOO because it will only affect their local copy.

提交回复
热议问题