在heroku上部署React App的展现页,而且这个React App须要node来作转发。node
基本的heroku配置能够直接参照文档。
若是是不须要node来作转发的单纯的create-react-app项目,能够直接参照官方文档的Deploying React with Zero Configuration,顺便附上github项目地址。
可是须要node作转发的项目,这个老哥一样给出了解决方案:heroku-cra-node。
下面来分析一下到底是如何配置的。react
先放上目录结构git
. ├── 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项目。github
在个人项目中外面的package.json以下express
{ "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起做用的是如下两句npm
"scripts": { "start": "node server", "heroku-postbuild": "cd react-ui/ && npm install && npm run build" },
heroku在检测到这是一个nodejs项目后,会自动执行npm start
,开启转发服务json
这里的heroku-postbuild
用到了npm的post-
钩子,在安装完依赖后,在npm start
以前,heroku环境下应该会执行npm run heroku
,此时会调用heroku-postbuild
这个命令。官方解释在此缓存
还有app
"cacheDirectories": [ "node_modules", "react-ui/node_modules" ],
根据文档,做用是在heroku上缓存下载好的npm包,就没必要每次更新的时候再从新npm i
了post
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
就能够啦