如何为babel-preset-react-app提供环境变量?(create-react-app+Express SSR场景)
Great question! When working with babel-preset-react-app in a server-side rendering (SSR) setup with Express, passing environment variables to the preset can be done in a few straightforward ways. Let's break them down based on your current code structure:
1. Inject Env Vars via Command Line & Configure Babel Preset
First, you can set environment variables when starting your Express server (use cross-env for cross-platform compatibility):
cross-env REACT_APP_API_URL=https://api.yourdomain.com NODE_ENV=production node bootstrap.js
Then, update your bootstrap.js to pass these variables to babel-preset-react-app and ensure they're available in your compiled code:
require('ignore-styles'); require('babel-register')({ ignore: [/(node_modules)/], presets: [ ['react-app', { // Adjust preset behavior based on env vars runtime: 'automatic', useESModules: process.env.NODE_ENV === 'production' }] ], // Inline specified env vars into compiled code plugins: [ ['transform-inline-environment-variables', { include: ['REACT_APP_API_URL', 'NODE_ENV'] }] ] }); require('./index');
2. Manually Set Env Vars in Code (Great for Debugging)
If you want to skip command-line args, set process.env variables at the very top of bootstrap.js before any other imports:
// Set env vars first process.env.NODE_ENV = process.env.NODE_ENV || 'development'; process.env.REACT_APP_CUSTOM_FEATURE = 'enabled'; require('ignore-styles'); require('babel-register')({ ignore: [/(node_modules)/], presets: ['es2015', 'react-app'] }); require('./index');
babel-preset-react-app will automatically pick up these variables to adjust its compilation logic (like enabling production optimizations when NODE_ENV=production).
3. Use .env Files (Match Create React App's Workflow)
To keep consistency with client-side CRA behavior, use the dotenv package to load variables from a .env file:
- Install the package:
npm install dotenv --save-dev
- Update
bootstrap.jsto load the.envfile upfront:
require('dotenv').config({ path: './.env' }); require('ignore-styles'); require('babel-register')({ ignore: [/(node_modules)/], presets: ['es2015', 'react-app'], plugins: [ ['transform-inline-environment-variables', { // Auto-include all CRA-style prefixed vars include: Object.keys(process.env).filter(key => key.startsWith('REACT_APP_')) }] ] }); require('./index');
Now you can define variables in a .env file just like you would in a standard CRA project:
REACT_APP_API_URL=https://api.yourdomain.com NODE_ENV=development
Quick Notes:
- Stick to
REACT_APP_prefix for custom variables to avoid conflicts with system environment variables (this is a CRA convention thatbabel-preset-react-apprespects). - The
NODE_ENVvariable is critical:babel-preset-react-appuses it to toggle production/development-specific optimizations.
内容的提问来源于stack exchange,提问作者Abhishek Kulshrestha

