如何将React构建产物部署到Laravel后端并配置运行
Hey there! Let’s get your React frontend hooked up to your Laravel backend so running php artisan serve loads your React app seamlessly. Here’s a step-by-step breakdown:
Laravel serves all static assets from the public/ directory, so we need to move your React build output here:
- Open your React project’s
build/folder (where you rannpm run build). - Copy all contents of this folder (including the
static/subfolder andindex.html) into your Laravel project’spublic/directory.- Pro tip: If you’re on macOS/Linux, use this command from your Laravel root:
cp -r /path/to/your/react/build/* ./public/ - On Windows, just drag-and-drop everything via File Explorer.
- Pro tip: If you’re on macOS/Linux, use this command from your Laravel root:
We need a template to serve React’s index.html content properly:
- In your Laravel project, make a new file at
resources/views/app.blade.php. - Open the
index.htmlfile now in Laravel’spublic/folder, copy all its content, and paste it intoapp.blade.php. - Update asset paths to use Laravel’s
asset()helper (this ensures paths work across environments):- Replace
<link href="/static/css/..."with<link href="{{ asset('static/css/...') }}" - Replace
<script src="/static/js/..."with<script src="{{ asset('static/js/...') }}" - Repeat this for any media file references in the HTML.
- Replace
Since React is a single-page app, we need to route all non-API requests to our new Blade view:
- Open
routes/web.phpin your Laravel project. - Add this catch-all route at the bottom of the file (so it doesn’t override existing web routes):
This tells Laravel to serve the React app for any URL not handled by another route (like your API endpoints).Route::get('/{any}', function () { return view('app'); })->where('any', '.*');
If you see 404 errors for CSS/JS files, React likely used absolute paths during the build. Fix this by:
- Updating your React project’s
package.jsonbuild script:"build": "react-scripts build --public-url ./", - Re-run
npm run buildand re-copy the files to Laravel’spublic/folder. Alternatively, set the environment variable before building:PUBLIC_URL=./ npm run build
You’re all set! Run this command in your Laravel project root:
php artisan serve
Visit http://localhost:8000 in your browser—your React app should render fully, and it’ll interact with your Laravel backend just like before.
Quick Troubleshooting Tips
- If API calls fail: Ensure your React app uses relative paths for API requests (e.g.,
/api/usersinstead ofhttp://localhost:8000/api/users) since everything’s now served from the same domain. - If you have existing Laravel web routes: Keep them above the catch-all route in
web.phpso they continue working as expected.
内容的提问来源于stack exchange,提问作者Gnanaseelan

