How do you share constants in NodeJS modules?

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

    From previous project experience, this is a good way:

    In the constants.js:

    // constants.js
    
    'use strict';
    
    let constants = {
        key1: "value1",
        key2: "value2",
        key3: {
            subkey1: "subvalue1",
            subkey2: "subvalue2"
        }
    };
    
    module.exports =
            Object.freeze(constants); // freeze prevents changes by users
    

    In main.js (or app.js, etc.), use it as below:

    // main.js
    
    let constants = require('./constants');
    
    console.log(constants.key1);
    
    console.dir(constants.key3);
    

提交回复
热议问题