如何在执行带--staging标识的npm build时为React应用添加「NON PRODUCTION」横幅,且生产构建不显示该横幅?
Got it, let's walk through a simple, reliable way to add that staging environment banner to your React app. This approach uses environment variables (built into Create React App) and a reusable component to conditionally show the banner only when you build for staging.
Step 1: Update Your Package.json Scripts
First, we'll add a dedicated staging build command that sets an environment variable. React automatically injects any variable prefixed with REACT_APP_ into your app, so we'll use that to flag the staging environment.
Open your package.json and update the scripts section:
"scripts": { "build": "react-scripts build", "build:staging": "REACT_APP_ENV=staging react-scripts build" }
Note for Windows Users
If you're on Windows, the direct environment variable syntax won't work. Install cross-env first to make it cross-platform:
npm install cross-env --save-dev
Then update the staging script:
"build:staging": "cross-env REACT_APP_ENV=staging react-scripts build"
Step 2: Create the Environment Banner Component
Make a new component that checks the environment variable and renders the banner only for staging.
Create a file called EnvironmentBanner.jsx (or .js if you don't use JSX):
import React from 'react'; import './EnvironmentBanner.css'; const EnvironmentBanner = () => { // Only render if we're in staging if (process.env.REACT_APP_ENV !== 'staging') { return null; } return ( <div className="staging-banner"> *NON PRODUCTION - STAGING ENVIRONMENT* </div> ); }; export default EnvironmentBanner;
Step 3: Add Styling for the Banner
To make the banner impossible to miss, add some CSS. Create EnvironmentBanner.css:
.staging-banner { position: fixed; top: 0; left: 0; width: 100%; background-color: #ffd700; color: #000; text-align: center; padding: 10px; font-weight: 700; font-size: 14px; z-index: 9999; /* Ensures it stays on top of other content */ }
Step 4: Add the Banner to Your Root Component
Import and render the banner at the top of your app's root component (usually App.jsx or index.jsx):
import EnvironmentBanner from './EnvironmentBanner'; function App() { return ( <> <EnvironmentBanner /> {/* Rest of your app content goes here */} <div className="app-content"> {/* ... */} </div> </> ); } export default App;
Testing It Out
- Run
npm run build:stagingto build for staging. When you open the builtindex.htmlfile, you'll see the banner at the top of the page. - Run
npm run buildfor production builds—the banner won't appear at all.
内容的提问来源于stack exchange,提问作者Vivek

