非create-react-app环境下,React如何读取.bashrc中的API密钥环境变量?
process.env.EXPO_YELP_API_KEY Undefined in Non-CRA React/Expo Projects Let's break down why your environment variable is coming up undefined and how to fix it step by step:
Step 1: Verify Your System Environment Variable is Active
First, make sure the key you added to .bashrc is actually available in your terminal:
- Open a new terminal window (existing terminals won't pick up
.bashrcchanges automatically) - Run this command to check:
echo $EXPO_YELP_API_KEY - If you don't see your key, run this to reload
.bashrc:
If it still fails, double-check yoursource ~/.bashrc.bashrcentry for typos (like missing quotes or misspelled variable names).
Step 2: Inject the Variable into Your Frontend Code
Frontend JavaScript doesn't have access to your system's process.env variables by default—your build tool needs explicit config to pass that value into your code. Here's how to do it based on your setup:
Option A: Using Webpack
Add Webpack's DefinePlugin to your webpack.config.js to replace process.env.EXPO_YELP_API_KEY with the actual value during bundling:
const webpack = require('webpack'); module.exports = { // ... your existing Webpack config plugins: [ new webpack.DefinePlugin({ 'process.env.EXPO_YELP_API_KEY': JSON.stringify(process.env.EXPO_YELP_API_KEY) }) ] };
Option B: Using Vite
In your vite.config.js, use the define option to inject the variable:
import { defineConfig } from 'vite'; export default defineConfig({ define: { 'process.env.EXPO_YELP_API_KEY': JSON.stringify(process.env.EXPO_YELP_API_KEY) } });
Option C: Using Expo (React Native)
Expo has its own pattern for environment variables. Use expo-constants to access the key:
- Install the package:
expo install expo-constants - Update your
expo.config.jsto expose the variable:module.exports = { // ... your existing Expo config extra: { yelpApiKey: process.env.EXPO_YELP_API_KEY } }; - Access it in your code like this:
import Constants from 'expo-constants'; const yelpApiKey = Constants.expoConfig.extra.yelpApiKey;
Step 3: Restart Your Development Server
After updating your config, completely stop and restart your dev server—build config changes won't take effect until you do this.
Step 4: Test the Variable
Add a console log to confirm the key is now available:
// For Webpack/Vite console.log('API Key:', process.env.EXPO_YELP_API_KEY); // For Expo console.log('API Key:', Constants.expoConfig.extra.yelpApiKey);
If the log shows your key, your axios request should authenticate correctly now.
Quick Note for Web Apps
If this is a web project (not React Native/Expo), keep in mind: the API key will still be visible in your bundled JavaScript code. For production, a better approach is to set up a backend proxy that forwards requests to Yelp using the key, so the key never leaves your server. But this fix works perfectly for development.
内容的提问来源于stack exchange,提问作者Michael Durrant




