I want to access the value of an environment variable in my JS file. I tried using the process.end.VAR_NAME method but it renders it as undefined. I can see the variable and its value by writing the SET command in my terminal but somehow cannot get the already existing value into my project. Please note that I do not have to initialize my variable, i just need to use an existing one into my project directly. Also, my project is not based on create-react-app, so is dotenv a possibility to make this work?
1 Answer
process.env only works for nodeJS, that's why it renders as undefined with react.
I guess you use webpack, if so, you can use webpack.DefinePlugin, which is very usefull to pass environment variable.
You can use it like that:
{
//...
plugins: [
new webpack.DefinePlugin({
'MY_GLOBAL_VARIABLE': JSON.stringify(process.env.MY_GLOBAL_VARIABLE)
})
]
//...
}
Thanks to that, the variable 'MY_GLOBAL_VARIABLE' is global and can be accessed everywhere in your code.
You can try it by typing console.log(MY_GLOBAL_VARIABLE) where you want (in a js file sure).
5 Comments
Shruti Upreti
Hi, I tried using that, but I still get it as undefined, do I need to add it in package.json and .eslintrc file as well?
Vashnak
Can you show me your webpack config please ? And the way you call your variable
Vashnak
Moreover, if you use eslint, you may need to set this config: "globals": { "ENV": false }
Shruti Upreti
I tried using the above method, I still get it as undefined, and I am calling it in my component just as GLOBAL_VARIABLE_NAME
Vashnak
Can you still please give me your webpack configuration. It is a known solution, you may have forgotten something ^^.