I understand that process.env only work on server-side, I want to use the same concept but in client side because my app is deployed on aws s3, I know that we can put a variable in process.env from webpack how I can do the same but in client side?
Loaded env variables are also exposed to your client source code via import.meta.env as strings.
Today we will learn how to use . env file in our react js project. If you are using some external APIs for data you must use the . env file to store your sensitive credentials like API keys.
Using a .env fileconst { REACT_APP_MY_ENV } = process. env; Assuming the application was created with create-react-app, this will work out of the box, with no additional work. If the application was not created with create-react-app, add the dotenv package to the project.
This is a quick tutorial on how to create and access environment variables in React with a dotenv ( . env ) file. React apps built with Create React App support dotenv environment variables out of the box, so all you need to do is add a . env file to the root folder of your React project.
You can use webpack.DefinePlugin
to put variables in process.env
. Below, most common example with React:
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': '"production"'
}
})
]
isn't it enough?
I've created this example to prove that it works:
// webpack.config.js
const webpack = require('webpack');
module.exports = {
entry: './index.js',
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': '"production"'
}
})
]
};
// index.js
console.log(process.env);
console.log(process.env.NODE_ENV);
and the output file of this configuration is like this:
// ... some internal webpack init function ...
([function(e,n){console.log(Object({NODE_ENV:"production"})),console.log("production")}]);
so as you may notice, values are replaced correctly.
If you need this variable you can do some initialization like:
global.myVar = process.env.NODE_ENV;
or something like this.
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