317

Currently I'm doing this:

foo.js

const FOO = 5;

module.exports = {
    FOO: FOO
};

And using it in bar.js:

var foo = require('foo');
foo.FOO; // 5

Is there a better way to do this? It feels awkward to declare the constant in the exports object.

Tower
  • 98,741
  • 129
  • 357
  • 507
  • 6
    If you want to export it, you put it in the `exports`. What's awkward about that? – Alex Wayne Dec 21 '11 at 20:00
  • 8
    I'm used to C# and PHP. I guess I just have to get used to defining each constant twice. Maybe in the future we will have `export const FOO = 5;`. – Tower Dec 21 '11 at 20:07
  • 2
    @Tower The future is now (ES2015)! http://www.2ality.com/2014/09/es6-modules-final.html#named_exports_%28several_per_module%29 – Spain Train Oct 02 '15 at 20:39
  • 1
    Is this functionally different from the more concise `module.exports={FOO:5};` ? – Joe Lapp Dec 29 '15 at 23:40
  • 3
    It does not only feel akward, it is no constant anymore – Ini May 07 '18 at 23:33
  • one little thing you can do to make the code look cleaner is when you require it, extract it like: `const { FOO } = require('foo')`. Then you can just call `FOO; \\5` instead of `foo.FOO; \\5`. Just be careful of requiring multiple files or modules with various objects named the same thing. Logically, though, as has been noted OP is doing this properly. – dillon.harless Mar 27 '20 at 14:58

13 Answers13

435

In my opinion, utilizing Object.freeze allows for a DRYer and more declarative style. My preferred pattern is:

./lib/constants.js

module.exports = Object.freeze({
    MY_CONSTANT: 'some value',
    ANOTHER_CONSTANT: 'another value'
});

./lib/some-module.js

var constants = require('./constants');

console.log(constants.MY_CONSTANT); // 'some value'

constants.MY_CONSTANT = 'some other value';

console.log(constants.MY_CONSTANT); // 'some value'
Spain Train
  • 5,890
  • 2
  • 23
  • 29
  • What should it look like if I need to export both constants and functions? Should I put functions in the freeze block too? – Tom Jun 09 '16 at 22:21
  • 4
    this approach is better because IDE autocomplete works with it. – David Aleksanyan Nov 14 '16 at 10:39
  • 1
    @Tom You sure can - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze#Examples – Spain Train Nov 17 '16 at 16:43
  • 8
    This is a great answer, but it might turn people away from this approach because of the outdated warning about v8's performance at the end. Please consider removing the warning. – sampathsris Jan 29 '18 at 08:57
  • 4
    Thanks @Krumia! I have updated it, but left the original warning text just for historical context (and because some of these comments wouldn't make sense without it). – Spain Train Jan 29 '18 at 21:01
  • any tricks to make AutoComplete pick up these new constants in VSCode? – Hicsy Jul 07 '20 at 17:30
  • One caveat only high level constant cannot be overridden but nested constants can be updated. My constant is an json object. – Apoorv Mote Oct 12 '20 at 11:38
173

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
Dominic Barnes
  • 28,083
  • 8
  • 65
  • 90
  • I know this is an old post but in the better example should you not have set writable to false? – Antoine Hedgecock Mar 01 '13 at 09:50
  • 2
    @AntoineHedgecock It's not necessary, check the documentation on [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty). All properties not specified are assumed `false` in this context. – Dominic Barnes Mar 01 '13 at 14:45
  • 6
    Also noteworthy, Object.freeze() – damianb Mar 11 '13 at 14:06
  • Be aware that both setting writable to false and using Object.freeze have a massive performance penalty in v8 - https://code.google.com/p/v8/issues/detail?id=1858 and http://jsperf.com/performance-frozen-object – Spain Train Jan 21 '14 at 04:00
  • Using the constants within the exporting module I see it needs to require itself. – Gunnar Forsgren - Mobimation Sep 15 '16 at 15:37
  • 1
    @SpainTrain This appears to have been fixed by https://codereview.chromium.org/135903014/ – Grinde Mar 14 '17 at 09:50
  • If someone try tu use this, "'value'" is a keyword reserved, cannot be change –  Jun 26 '21 at 10:46
  • In my experimentation, this is the only solution that actually prevents the callers from changing the constant values. Very elegant. Has anyone figured out how this could be tweaked to preserve the constant behaviour, but also allow IntelliSense to know about the defined constants? I'm guessing it's not possible since execution is necessary :( – eFail Sep 11 '21 at 00:32
163

ES6 way.

export in foo.js

const FOO = 'bar';
module.exports = {
  FOO
}

import in bar.js

const {FOO} = require('foo');
Isk1n
  • 371
  • 2
  • 6
Diego Mello
  • 5,220
  • 3
  • 17
  • 21
  • 68
    Yes. Stack Overflow needs a way to depreciate outdated answers. – Rick Jolly Apr 13 '17 at 17:31
  • 10
    Note that it is the `const` in `bar.js` that enforces immutability of the destructured variable, not the `const` in `foo.js`. That is, one can use `let {FOO} =` in `bar.js` and mutate the "constant" variable. AFAIK, to enforce immutability of exports, one still needs either ES modules or `Object.freeze`. – Spain Train Aug 11 '17 at 21:59
  • One can also change `FOO` inside `foo.js`. – lima_fil Sep 11 '17 at 16:37
110

You can explicitly export it to the global scope with global.FOO = 5. Then you simply need to require the file, and not even save your return value.

But really, you shouldn't do that. Keeping things properly encapsulated is a good thing. You have the right idea already, so keep doing what you're doing.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • 61
    I'm sorry to do this, but -1 for knowing better but not providing an alternative (better) solution; (re: "But really, you shouldn't do that. Keeping things properly encapsulated is a good thing.") – Mulan Aug 18 '13 at 17:05
  • 25
    If the entire software development community thought this way, we'd still be using punchards. Fortunately there are a few mavericks out there who know when it's better to break the insane rules we impose on ourselves. If encapsulation is useful, use it. If it's a nervous nanny stopping you do your job, fire the nervous nanny and get on with it. – unsynchronized Jul 04 '14 at 19:16
  • 27
    @naomik (super late reply time) The real reason that I didn't provide a better solution is because the OP already knows the solution. Encapsulate things in their own module and require them where necessary. – Alex Wayne Sep 17 '14 at 21:46
  • 2
    Then this is not an actual answer and should rather be an explanation comment stating "you're doing good enough, alternatives are bad".. – Andrey Popov Sep 15 '15 at 13:54
  • 1
    Wrong application of encapsulation. When a class uses special values as indicators and gives them a name, you WANT to share that with any code that makes use of that class. – grantwparks Jun 11 '16 at 14:46
  • 1
    @unsynchronized and then realise later on that you wish you didn't fire her ;p – Nodeocrat Nov 27 '16 at 18:47
  • 1
    It seems you can still change foo.FOO in the bar.js file. For example, I can do foo.FOO = 55. So it doesn't seem to really be a constant. – dcp Jul 26 '17 at 18:17
  • An alternative to the `global.FOO` is that you just define `const FOO = 'bar'`, then read the source code from other files and `eval` them in the file where `FOO` is defined. I know this sounds crazy and dangerous, but if what you are doing has nothing to do with user input (e.g. a pure UI test project), this works pretty good. – Aetherus Oct 29 '18 at 02:14
20

import and export (prob need something like babel as of 2018 to use import)

types.js

export const BLUE = 'BLUE'
export const RED = 'RED'

myApp.js

import * as types from './types.js'

const MyApp = () => {
  let colour = types.RED
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

atreeon
  • 21,799
  • 13
  • 85
  • 104
18

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);
Manohar Reddy Poreddy
  • 25,399
  • 9
  • 157
  • 140
16

I found the solution Dominic suggested to be the best one, but it still misses one feature of the "const" declaration. When you declare a constant in JS with the "const" keyword, the existence of the constant is checked at parse time, not at runtime. So if you misspelled the name of the constant somewhere later in your code, you'll get an error when you try to start your node.js program. Which is a far more better misspelling check.

If you define the constant with the define() function like Dominic suggested, you won't get an error if you misspelled the constant, and the value of the misspelled constant will be undefined (which can lead to debugging headaches).

But I guess this is the best we can get.

Additionally, here's a kind of improvement of Dominic's function, in constans.js:

global.define = function ( name, value, exportsObject )
{
    if ( !exportsObject )
    {
        if ( exports.exportsObject )
            exportsObject = exports.exportsObject;
        else 
            exportsObject = exports;        
    }

    Object.defineProperty( exportsObject, name, {
        'value': value,
        'enumerable': true,
        'writable': false,
    });
}

exports.exportObject = null;

In this way you can use the define() function in other modules, and it allows you to define constants both inside the constants.js module and constants inside your module from which you called the function. Declaring module constants can then be done in two ways (in script.js).

First:

require( './constants.js' );

define( 'SOME_LOCAL_CONSTANT', "const value 1", this ); // constant in script.js
define( 'SOME_OTHER_LOCAL_CONSTANT', "const value 2", this ); // constant in script.js

define( 'CONSTANT_IN_CONSTANTS_MODULE', "const value x" ); // this is a constant in constants.js module

Second:

constants = require( './constants.js' );

// More convenient for setting a lot of constants inside the module
constants.exportsObject = this;
define( 'SOME_CONSTANT', "const value 1" ); // constant in script.js
define( 'SOME_OTHER_CONSTANT', "const value 2" ); // constant in script.js

Also, if you want the define() function to be called only from the constants module (not to bloat the global object), you define it like this in constants.js:

exports.define = function ( name, value, exportsObject )

and use it like this in script.js:

constants.define( 'SOME_CONSTANT', "const value 1" );
xmak
  • 1,060
  • 9
  • 8
8

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' } }

Luis Martins
  • 1,572
  • 12
  • 11
5

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.

herman
  • 11,740
  • 5
  • 47
  • 58
3

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
});
Eloquence
  • 51
  • 3
3

Since Node.js is using the CommonJS patterns, you can only share variables between modules with module.exports or by setting a global var like you would in the browser, but instead of using window you use global.your_var = value;.

alessioalex
  • 62,577
  • 16
  • 155
  • 122
0

I recommend doing it with webpack (assumes you're using webpack).

Defining constants is as simple as setting the webpack config file:

var webpack = require('webpack');
module.exports = {
    plugins: [
        new webpack.DefinePlugin({
            'APP_ENV': '"dev"',
            'process.env': {
                'NODE_ENV': '"development"'
            }
        })
    ],    
};

This way you define them outside your source, and they will be available in all your files.

galki
  • 8,149
  • 7
  • 50
  • 62
0

I don't think is a good practice to invade the GLOBAL space from modules, but in scenarios where could be strictly necessary to implement it:

Object.defineProperty(global,'MYCONSTANT',{value:'foo',writable:false,configurable:false});

It has to be considered the impact of this resource. Without proper naming of those constants, the risk of OVERWRITTING already defined global variables, is something real.

colxi
  • 7,640
  • 2
  • 45
  • 43