Declare Global constants with Babel ES6
In modern web applications, there are multiple ways to declare and use the global constants. But if you using Babel (or any other JS Transpiler), you can manage these constants in a very easy and efficient way.
Why to use a constant?
The main reason to use a constant is for safer and cleaner code.
Use case: A literal / object or property being used several times within the application and is fixed.
Simplest way to declare constants
STEP 1: Create a constants.js file
Declare your constants in a JSON key:pair object inside module.exports which will export all the constants, that can be import anywhere.
module.exports = {
API_BASE_URL: ‘https://api.xyz.com/',
APP_VERSION: ‘2.3.0’,
APP_ENVIRONMENT: ‘Production',
...
};
STEP 2: Import the desired constant pair
Now, wherever we need to use these constants, we can simply import them and use directly.
import { API_BASE_URL , APP_VERSION } from “../path/to/constants.js”...
console.log( APP_VERSION ); // will log the constant's value.
If we need to use multiple constants in a same file, this will be preferred to import all at once:
import C from “../path/to/constants.js”...
console.log( C.APP_VERSION );
console.log( C.APP_ENVIRONMENT );
Points to remember
- A global configuration can declared using this way.
- Constants are not in replace of store/s. Store/s are variables, which can even change their values and the concept is entirely different from constants.
- It is not mandatory to use a constant name in UPPER_CASE, while it is recommended, to distinguish them from variables.
Other ways to declare global constants
There are many other ways, to achieve the same, while they aren’t recommended.
- By adding value to the localStorage/ sessionStorage:
window.localStorage.setItem( “APP_VERSION” , ’2.3.0’ )
...
console.log( window.localStorage.getItem( "APP_VERSION" ) );
2. By allocating it to the DOM:
window.API_VERSION = ‘2.3.0’
…
console.log( window.API_VERSION );
3. By passing it down to every component.
<ComponentName API_VERSION=’2.3.0’ />