This article will show how you can share constants in NodeJS modules.
Sharing constants in Node.js modules is a common requirement in projects to maintain a clean and organized codebase. There are various approaches suggested by the community, and in this tutorial, we’ll explore different methods to share constants while emphasizing best practices.
Using Object.freeze
The Object.freeze method is a simple and effective way to create constants in Node.js. This method prevents modifications to the object, making it immutable. Follow these steps:
./lib/constants.js
// constants.js
module.exports = Object.freeze({
MY_CONSTANT: 'some value',
ANOTHER_CONSTANT: 'another value'
});
Explanation:
- In this method, a module is created in the
constants.jsfile usingObject.freeze. Object.freezeis a method in JavaScript that prevents the modification of an object. It makes the object immutable.- The module exports an object containing key-value pairs, representing the constants.
- By using
Object.freeze, any attempt to modify the constants after their declaration will have no effect.
./lib/some-module.js
// some-module.js
var constants = require('./constants');
console.log(constants.MY_CONSTANT); // 'some value'
// Attempting to modify will have no effect
constants.MY_CONSTANT = 'some other value';
console.log(constants.MY_CONSTANT); // 'some value'
Explanation:
- In
some-module.js, the constants module is imported usingrequire. - The constants are accessed and used in the application.
- An attempt to modify a constant value (
constants.MY_CONSTANT) is demonstrated, and it shows that the value remains unchanged due to the use ofObject.freeze.
This method provides a simple and effective way to create constants with immutability.
Using Object.defineProperty
If you want to enforce true constants and prevent any modifications, you can use Object.defineProperty. This method provides more control over the properties of the object.
./lib/constants.js
// constants.js
function define(name, value) {
Object.defineProperty(exports, name, {
value: value,
enumerable: true,
writable: false,
configurable: false
});
}
define("PI", 3.14);
Explanation:
- This method uses
Object.definePropertyto create constants with more control over their properties. - The
definefunction is created to encapsulate the definition process. It usesObject.definePropertyto set properties likevalue,enumerable,writable, andconfigurable. - In this example, a constant
PIis defined with a value of3.14, and it’s made non-writable and non-configurable.
./lib/script.js
// script.js
var constants = require("./constants");
console.log(constants.PI); // 3.14
// Attempting to modify will have no effect
constants.PI = 5;
console.log(constants.PI); // still 3.14
Explanation:
- In
script.js, the constants module is imported, and thePIconstant is accessed and used. - An attempt to modify the value of
PIis demonstrated, and it shows that the value remains unchanged due to the non-writable property set during definition.
This method ensures that constants are truly read-only.
Using ES6 export and import
For a more modern approach, using ES6 syntax with export and import is an excellent choice.
./types.js
// types.js export const BLUE = 'BLUE'; export const RED = 'RED';
Explanation:
- This method utilizes ES6
exportto define and export constants from a module. - Constants
BLUEandREDare exported from thetypes.jsmodule. - ES6
exportallows for a cleaner and more modern syntax for module exports.
./myApp.js
// myApp.js
import * as types from './types.js';
const MyApp = () => {
let colour = types.RED;
}
Explanation:
- In
myApp.js, constants are imported using ES6import. - The
import * as typessyntax imports all exports from thetypes.jsmodule into thetypesobject. - Constants like
REDcan be accessed using thetypesobject.
This method leverages modern ES6 syntax for cleaner and more readable code.
Global Scope (Not Recommended)
While it’s possible to export constants to the global scope, it’s generally not recommended due to potential issues with encapsulation.
However, if you still want to proceed.
./constants.js
// constants.js
'use strict';
let constants = {
key1: "value1",
key2: "value2",
key3: {
subkey1: "subvalue1",
subkey2: "subvalue2"
}
};
global.constants = Object.freeze(constants);
Explanation:
- This method exports constants to the global scope, making them accessible throughout the application.
- The
global.constantsobject is assigned the value of the constants object, andObject.freezeis used to make it immutable. - Exporting constants globally is generally discouraged to maintain proper encapsulation.
Each method offers a different approach to sharing constants in Node.js, and the choice depends on project requirements and coding preferences. It’s essential to consider factors like immutability, readability, and maintainability when selecting a method.