How do you share constants in NodeJS modules?

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

    Technically, const is not part of the ECMAScript specification. Also, using the "CommonJS Module" pattern you've noted, you can change the value of that "constant" since it's now just an object property. (not sure if that'll cascade any changes to other scripts that require the same module, but it's possible)

    To get a real constant that you can also share, check out Object.create, Object.defineProperty, and Object.defineProperties. If you set writable: false, then the value in your "constant" cannot be modified. :)

    It's a little verbose, (but even that can be changed with a little JS) but you should only need to do it once for your module of constants. Using these methods, any attribute that you leave out defaults to false. (as opposed to defining properties via assignment, which defaults all the attributes to true)

    So, hypothetically, you could just set value and enumerable, leaving out writable and configurable since they'll default to false, I've just included them for clarity.

    Update - I've create a new module (node-constants) with helper functions for this very use-case.

    constants.js -- Good

    Object.defineProperty(exports, "PI", {
        value:        3.14,
        enumerable:   true,
        writable:     false,
        configurable: false
    });
    

    constants.js -- Better

    function define(name, value) {
        Object.defineProperty(exports, name, {
            value:      value,
            enumerable: true
        });
    }
    
    define("PI", 3.14);
    

    script.js

    var constants = require("./constants");
    
    console.log(constants.PI); // 3.14
    constants.PI = 5;
    console.log(constants.PI); // still 3.14
    

提交回复
热议问题