You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用create-react-app运行生产构建版本而非开发构建?

Running Your Create-React-App Production Build

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:

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 serve globally (you only need to do this once):
    npm install -g serve
    
  • Navigate to your project’s root directory, then run:
    serve -s build
    
    The -s flag tells serve to redirect all unknown paths to index.html—perfect for single-page apps. By default, it’ll run on port 3000. To use a different port, add the -l flag:
    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:

  1. Install Express as a dev dependency:
    npm install express --save-dev
    
  2. Create a file named server.js in 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}`);
    });
    
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:52:06