将React项目部署在heroku上展示

1,621 阅读2分钟

『 文章首发于GitHub Blog

目的

在heroku上部署React App的展示页,并且这个React App需要node来做转发。

思考

基本的heroku配置可以直接参照文档。 如果是不需要node来做转发的单纯的create-react-app项目,可以直接参照官方文档的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,开启转发服务

image

这里的heroku-postbuild用到了npm的post-钩子,在安装完依赖后,在npm start之前,heroku环境下应该会执行npm run heroku,此时会调用heroku-postbuild这个命令。官方解释在此

image

还有

  "cacheDirectories": [
    "node_modules",
    "react-ui/node_modules"
  ],

根据文档,作用是在heroku上缓存下载好的npm包,就不必每次更新的时候再重新npm i

image

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就可以啦