My CRA project isn't parsing my environment variables. I see this in the docs:
By default you will have NODE_ENV defined for you, and any other environment variables starting with REACT_APP_
And here is some code for testing:
// .env in the project root folder
REACT_APP_GOOGLE=google.com
REACT_APP_API_POST_URL=http://localhost:4000/api/
// App.js
import dotenv from 'dotenv';
componentDidMount() {
if (dotenv.error) {
console.log('dotenv.error', dotenv.error);
} else { console.log('dotenv.parsed', dotenv.parsed); // undefined
}
}
// App.js insider render()
<button
onClick={e => {
e.preventDefault();
console.log("process.env", process.env); //
// {NODE_ENV: "development", PUBLIC_URL: ""}
// NODE_ENV: "development"
// PUBLIC_URL: ""
console.log("process.env.NODE_ENV", process.env.NODE_ENV); // development
console.log("process.env.REACT_APP_GOOGLE", process.env.REACT_APP_GOOGLE); // undefined
}}
>log .env</button>
Anyone know why it's not parsing the env variables?
Here is your component:
import React, { Component } from 'react';
import './App.css';
const googleEnvVariable = process.env.REACT_APP_GOOGLE;
class App extends Component {
render() {
return <div className="App">{googleEnvVariable}</div>;
}
}
export default App;
And here is your .env
REACT_APP_GOOGLE=hereisyourenvvar
You should see hereisyourenvvar
EDIT: updated answer to display on the screen instead of the console.log...
From the code you gave, it seems like you forgot to call the config
function (unless you didn't show it). If you want your .env
to be implemented, you will have to do the following at the top level of your project :
import dotenv from 'dotenv';
// Load ENV vars
const dotEnvOptions = {
path: 'env/dev.env' //Example path relative to your project folder
}
dotenv.config(dotEnvOptions)
To figure out what is going wrong you may turn on logging to help debug why certain keys or values are not being set as you expect :
dotenv.config({ debug: true })
From there, if a path/variable isnt recognized, it will be printed int he console :
If you are not seeing anything, it either means that your path is wrong or that the code isn't executed
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.