React项目中.env文件仅首个变量可用,其余变量无法访问
Hey, I see exactly what's going on here! The problem boils down to Create React App's environment variable naming rules—only variables prefixed with REACT_APP_ get injected into your application by react-scripts. Your second variable APP_BASE_URL is missing this required prefix, which is why it's not showing up in process.env.
Here's how to fix it:
- Update your .env file to add the
REACT_APP_prefix to all variables you want to access in your app:
REACT_APP_PORT=44318 REACT_APP_BASE_URL=https://localhost:44318/
Pro tip: While you can separate variables with semicolons on one line, splitting them into individual lines makes your config way easier to read and maintain.
- Restart your development server! This is crucial—
react-scriptsonly loads .env variables when you first start the server. If you don't restart after modifying the file, the changes won't take effect. Just stop your currentnpm startprocess and run it again.
Why this happens:
Create React App enforces the REACT_APP_ prefix to prevent conflicts with system-level environment variables. It ensures that only the variables you explicitly designate as part of your React app get bundled into your code. The first variable worked purely by coincidence because it already had the correct prefix—this isn't about being the "first" variable in the file at all.
To verify it works:
After restarting, check your console again with your component code (I cleaned it up a bit for clarity):
import { useEffect } from 'react'; export default () => { useEffect(() => { console.log('All env vars:', process.env); console.log('Base URL:', process.env.REACT_APP_BASE_URL); }, []); return <div>Check your browser console for the output!</div>; };
You should now see both REACT_APP_PORT and REACT_APP_BASE_URL listed in the process.env object.
内容的提问来源于stack exchange,提问作者Yener

