將React項目部署在heroku上展現

目的

在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

在個人項目中外面的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

clipboard.png

這裏的heroku-postbuild用到了npm的post-鉤子,在安裝完依賴後,在npm start以前,heroku環境下應該會執行npm run heroku,此時會調用heroku-postbuild這個命令。官方解釋在此緩存

clipboard.png

還有app

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

根據文檔,做用是在heroku上緩存下載好的npm包,就沒必要每次更新的時候再從新npm i
clipboard.pngpost

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就能夠啦

相關文章
相關標籤/搜索