How do you share constants in NodeJS modules?

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

    I ended up doing this by exporting a frozen object with anonymous getter functions, rather than the constants themselves. This reduces the risk of nasty bugs introduced due to a simple typo of the const name, as a runtime error will be thrown in case of a typo. Here's a full example that also uses ES6 Symbols for the constants, ensuring uniqueness, and ES6 arrow functions. Would appreciate feedback if anything in this approach seems problematic.

    'use strict';
    const DIRECTORY = Symbol('the directory of all sheets');
    const SHEET = Symbol('an individual sheet');
    const COMPOSER = Symbol('the sheet composer');
    
    module.exports = Object.freeze({
      getDirectory: () => DIRECTORY,
      getSheet: () => SHEET,
      getComposer: () => COMPOSER
    });
    

提交回复
热议问题