I am trying to modify some variables in my React app according to the environment.
I started using .env
file, I have tried all solutions in react evironment variables .env return undefined but with no success.
I am using VS2019, and did the following:
I added
dotenv
modules. This is a portion of mypackage.json
file:"dependencies": { "@azure/msal-browser": "^2.16.1", "@azure/msal-react": "^1.0.1", "axios": "^0.21.1", "bootstrap": "^5.1.0", "dotenv": "^10.0.0", "express": "^4.17.1", "jwt-decode": "^3.1.2", "react": "^17.0.2", "react-bootstrap": "^1.6.1", "react-cookie": "^4.1.1", "react-dom": "^17.0.2" }, "scripts": { "clean": "", "build": "webpack-cli ./src/index.jsx --config webpack.config.js" }
Then I edited the
server.json
file. I added the line:require('dotenv').config() app.use('/', express.static('dist', { index: "index.html" }))
I also modified the file
webpack.config.js
:const webpack = require('webpack') .... resolve: { extensions: ['.Webpack.js', '.web.js', '.ts', '.js', '.jsx', '.tsx'] }, plugins: [ new webpack.DefinePlugin({ BASE_URL_API: JSON.stringify('https://***.azurewebsites.net'), BASE_URL_API_ENV: JSON.stringify(process.env.REACT_APP_BASE_URL_API), }) ]
Finally I added 3
.env
file in the root folder of the project:.env
,.env.development
and.env.production
.
The content, at the moment, is the same for all files. I have used one of three lines below, not all three lines together:
REACT_APP_BASE_URL_API = https://***.azurewebsites.net
REACT_APP_BASE_URL_API = 'https://***.azurewebsites.net'
REACT_APP_BASE_URL_API = "https://***.azurewebsites.net"
Finally I use the variable in this way:
import axios from 'axios'; export const axiosClient = axios.create({ baseURL: BASE_URL_API_ENV //baseURL: BASE_URL_API <-- This Line Works but it is not what I need });
Now when I start the project by VS2019, this command is launched: webpack-cli ./src/index.jsx --config webpack.config.js
(it is that one defined in package.json
file). But if I manually start the project with the command npm start
I get same result:
process.env
is undefined.
And the bundled file is that:
What's wrong?