如何使用create-react-app运行生产构建版本而非开发构建?
Hey there! Glad you’ve got your React app polished and built with npm run build—getting that production bundle up and running is super straightforward. Here are the most common, reliable methods to do it:
Method 1: Use the Official serve Package (Recommended)
Create React App’s docs specifically recommend this lightweight static server for serving production builds. It handles routing correctly (critical if you’re using React Router) and is easy to set up:
- First, install
serveglobally (you only need to do this once):npm install -g serve - Navigate to your project’s root directory, then run:
Theserve -s build-sflag tellsserveto redirect all unknown paths toindex.html—perfect for single-page apps. By default, it’ll run on port 3000. To use a different port, add the-lflag:serve -s build -l 4000
Method 2: Use npx to Avoid Global Installation
If you don’t want to install serve globally, you can run it directly with npx (which comes with npm 5.2+):
npx serve -s build
This will download and run serve temporarily without cluttering your global packages.
Method 3: Build a Simple Node.js Server with Express
If you prefer a custom setup, you can create a tiny Express server to serve your build folder:
- Install Express as a dev dependency:
npm install express --save-dev - Create a file named
server.jsin your project root with this code:const express = require('express'); const path = require('path'); const app = express(); // Serve static files from the build directory app.use(express.static(path.join(__dirname, 'build'))); // Handle React routing: redirect all requests to index.html app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'build', 'index.html')); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Production server running on http://localhost:${PORT}`); }); - Start the server with:
node server.js
Important Note
Don’t try to open the build/index.html file directly in your browser! React apps (especially those with client-side routing) rely on a server to handle URL paths correctly—opening the file directly will cause routing errors and broken assets.
内容的提问来源于stack exchange,提问作者Raj

