如何在Travis CI构建通过后将Node Express+React应用部署至Heroku
Got it, let's get your Node/React app deployed to Heroku automatically after a successful Travis CI build. Let's break this down step by step, starting with fixing your .travis.yml and covering all necessary setup.
Step 1: Prep Heroku & Travis CI Integration
First, make sure you've got these prerequisites sorted:
- You’ve created a Heroku app (either via the Heroku CLI or web dashboard)
- You’ve linked your GitHub repo to both Travis CI and Heroku
- In Travis CI’s repo settings, add your Heroku API key as an environment variable named
HEROKU_API_KEY(you can grab this from your Heroku account settings) - Add your Heroku app name as
HEROKU_APP_NAMEin Travis env vars (using env vars is cleaner than hardcoding, but either works)
Step 2: Fix & Complete Your .travis.yml
Your current config has a few gaps (like starting the server in before_install which isn’t needed for CI, and incomplete scripts). Here’s the full, corrected version with deployment logic:
language: node_js node_js: - "stable" # Uses the latest stable Node.js version cache: directories: - node_modules - client/node_modules # Cache client dependencies to speed up builds install: - npm install # Install server-side dependencies - cd client && npm install && npm run build # Install client deps + build production React bundle - cd .. # Navigate back to root directory script: - npm run test # Run server-side tests (if you have them) - cd client && npm run test && npm run lint # Run client tests and linting - cd .. # Return to root deploy: provider: heroku api_key: $HEROKU_API_KEY # Uses the env var you set in Travis app: $HEROKU_APP_NAME # Your Heroku app name on: branch: main # Only deploy when the main branch builds successfully skip_cleanup: true # Critical! Prevents Travis from deleting the built React files before deployment
Key Fixes & Explanations:
installsection: Replaced your disjointedbefore_install/before_scriptwith a clear flow—we install server dependencies first, then handle the client: install its deps and build the production bundle (this creates theclient/buildfolder we’ll serve via Express).scriptsection: Runs both server and client tests/linting to ensure the build is valid before deployment.deploysection: Adds the Heroku provider, uses your stored API key, and triggers deployment only on successful main branch builds. Theskip_cleanup: trueis non-negotiable—without it, Travis will delete theclient/buildfolder right before deploying, leaving Heroku with no static files to serve.
Step 3: Update Your Express Server to Serve React's Production Build
You need to configure your Express server to serve the React static files and handle client-side routing. Add this to your index.js (or server entry file):
const path = require('path'); // Serve static files from the React app's build directory app.use(express.static(path.join(__dirname, 'client/build'))); // Handle React routing: return all requests to the React app's index.html app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'client/build', 'index.html')); }); // Listen on the port Heroku provides (or 5000 for local development) const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
Also, update your root package.json to include a start script that Heroku will use:
{ "scripts": { "start": "node index.js", // ... your other existing scripts } }
Step 4: Test the Deployment Flow
- Push your updated
.travis.yml, server code, andpackage.jsonchanges to your main branch - Head to Travis CI and watch the build run—if all tests/linting pass, it will automatically trigger deployment to Heroku
- Once deployment finishes, visit your Heroku app URL to confirm everything loads correctly
Troubleshooting Tips:
- If the React app doesn’t load on Heroku, check the Heroku logs (
heroku logs --tailvia CLI) to see if theclient/buildfolder exists or if there’s an issue with static file serving. - Double-check that your client’s
package.jsonhas a validbuildscript (create-react-app includes this by default, but it never hurts to verify). - If Travis fails during deployment, confirm your
HEROKU_API_KEYandHEROKU_APP_NAMEenv vars are set correctly in Travis settings.
内容的提问来源于stack exchange,提问作者GeraltDieSocke

