在部署React应用到Heroku时出现应用错误可能有多种原因。以下是一些可能的解决方法和代码示例:
npm run build
命令来构建生产版本的应用。在package.json
文件中添加以下脚本命令:"scripts": {
"build": "react-scripts build"
}
package.json
文件中添加一个engines
字段,指定您的应用所需的Node.js版本。例如:"engines": {
"node": "14.x"
}
.gitignore
文件,并且其中包含了build
文件夹。这样可以避免将构建后的文件提交到Git仓库中。示例:# .gitignore
build/
在Heroku上创建一个新的应用,并将您的代码仓库与该应用关联。
在Heroku的设置页面中,确保已添加了heroku/nodejs
buildpack。
确保您的项目根目录下有一个Procfile
文件,并在其中指定启动命令。示例:
# Procfile
web: node server.js
server.js
文件,并在其中配置一个简单的Express服务器来提供静态文件。示例:// server.js
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')));
// The "catchall" handler: for any request that doesn't
// match one above, send back React's index.html file.
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
NPM_CONFIG_PRODUCTION
的环境变量,并将其值设置为false
。这将确保安装开发依赖项。重新部署应用后,应该能够在Heroku上成功运行React应用。