In Redux, we can use props
as a constant, and state
as a global variable. But what do we have to use when we need a global constant?
Below is the options that I can consider.
Which one would assure the most proper architecture? And can you tell me the reason?
I would suggest the Option 3.
Reasons:
Maintainability - You just have to change this file and it will be made available across all the modules that use this so modifying is really easy.
Availability - Since this acts like a separate module it's very easy to import and use it.
Debugging - Compared to other options there isn't much hassle while debugging since everything that is within the module is easily accessible as we wrote it in the first place.
I will also suggest option 3.
As you can separate out the global constants at one place and can change them without touching the code. Just need to rebuild the project.
You can use webpack for this. Approach is very simple-
Define your global constants in a file lets say constants.js and export them. Lets say you want to configure API_KEY constant globally
const API_KEYS= {
production: JSON.stringify('prod-const'),
development: JSON.stringify('dev-const'),
test: JSON.stringify('test-const')
};
// based on the node env variable set by you get available environment setting
const environment = function () {
switch(process.env.NODE_ENV) {
case 'production':
return 'production';
case 'development':
return 'development';
case 'test':
return 'test';
default: // in case ...
return 'development';
};
};
// Helper method to get const value based on env
const mapEnvToConstants = function (consts) {
return consts[environment()];
};
// Use webpack to generate the build based on the env variable set // webpack config
module.exports = {
// ...
plugins: [
new webpack.DefinePlugin({
'const1': mapEnvToConstants(API_KEYS)
})
],
// ...
}
If you want to point to a different env variable or constant you need to rebuild the project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With