How do you share constants in NodeJS modules?

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

    I think that const solves the problem for most people looking for this anwwer. If you really need an immutable constant, look into the other answers. To keep everything organized I save all constants on a folder and then require the whole folder.

    src/main.js file

    const constants = require("./consts_folder");
    

    src/consts_folder/index.js

    const deal = require("./deal.js")
    const note = require("./note.js")
    
    
    module.exports = {
      deal,
      note
    }
    

    Ps. here the deal and note will be first level on the main.js

    src/consts_folder/note.js

    exports.obj = {
      type: "object",
      description: "I'm a note object"
    }
    

    Ps. obj will be second level on the main.js

    src/consts_folder/deal.js

    exports.str = "I'm a deal string"
    

    Ps. str will be second level on the main.js

    Final result on main.js file:

    console.log(constants.deal); Ouput:

    { deal: { str: 'I\'m a deal string' },

    console.log(constants.note); Ouput:

    note: { obj: { type: 'object', description: 'I\'m a note object' } }

    0 讨论(0)
提交回复
热议问题