将React项目部署在heroku上展示
fi3ework opened this issue · comments
目的
在 heroku 上部署 React App 的展示页,并且这个 React App 需要 node 来做转发。
思考
基本的 heroku 配置可以直接参照 文档。
如果是不需要 node 来做转发的单纯的 react 项目,可以直接参照官方文档的 Deploying React with Zero Configuration,顺便附上 GitHub项目地址。
但是需要 node 做转发的项目,这个老哥同样给出了解决方案:heroku-cra-node。
下面来分析一下究竟是如何配置的。
分析
先放上目录结构
.
├── LICENSE
├── README.md
├── package-lock.json
├── package.json
├── react-ui
│ ├── LICENSE
│ ├── README.md
│ ├── build
│ ├── config
│ ├── doc
│ ├── node-proxy
│ ├── package.json
│ ├── public
│ ├── scripts
│ ├── src
│ └── tsconfig.json
└── server
└── index.js
简单来说,就是外面的 package.json 对 node 的包,react-ui 文件夹对应的是整个 react 项目。
外面的 package.json
在我的项目中外面的 package.json 如下
{
"name": "heroku-cra-node",
"version": "1.0.0",
"description": "How to use create-react-app with a custom Node API on Heroku",
"engines": {
"node": "6.11.x"
},
"scripts": {
"start": "node server",
"heroku-postbuild": "cd react-ui/ && npm install && npm run build"
},
"cacheDirectories": [
"node_modules",
"react-ui/node_modules"
],
"dependencies": {
"express": "^4.14.1",
"superagent": "^3.8.2"
},
"repository": {
"type": "git",
"url": "https://github.com/mars/heroku-cra-node.git"
},
"keywords": [
"node",
"heroku",
"create-react-app",
"react"
],
"license": "MIT",
"devDependencies": {}
}
对 heroku 起作用的是以下两句
"scripts": {
"start": "node server",
"heroku-postbuild": "cd react-ui/ && npm install && npm run build"
},
heroku 在检测到这是一个 nodejs 项目后,会自动执行 npm start
,开启转发服务
这里的 heroku-postbuild
用到了 npm 的 post-
钩子,在安装完依赖后,在 npm start
之前,heroku 环境下应该会执行 npm run heroku
,此时会调用 heroku-postbuild
这个命令。官方解释 在此
还有
"cacheDirectories": [
"node_modules",
"react-ui/node_modules"
],
根据 文档,作用是在 heroku 上缓存下载好的 npm 包,就不必每次更新的时候再重新 npm i
了
server/index.js
app.set('port', (process.env.PORT || 8081))
app.use(express.static(path.resolve(__dirname, '../react-ui/build')));
重点是这两句话,第一句是指定端口,如果是在 heroku 中部署的话,端口是动态分配的,所以要使用 process.env.PORT
,本地的话自动变为 8081。
第二句是指定静态文件的位置。
总结
把上述文件配置好之后,推送到 heroku,再 heroku open
就可以啦。