我如今有一個項目是這樣的,前端是用 React 寫的,後端是用 Nodejs,目錄結構以下:前端
1 . 2 ├── README.md 3 ├── backend 4 ├── node_modules 5 ├── package.json 6 ├── public 7 ├── src 8 └── yarn.lock
這個 package.json
的內容以下:node
1 { 2 "name": "crudtest", 3 "version": "0.1.0", 4 "private": true, 5 "dependencies": { 6 "classnames": "^2.2.5", 7 "concurrently": "^3.5.1", 8 "react": "^16.2.0", 9 "react-dom": "^16.2.0", 10 "react-redux": "^5.0.7", 11 "react-router-dom": "^4.2.2", 12 "react-scripts": "1.1.1", 13 "redux": "^3.7.2", 14 "redux-thunk": "^2.2.0" 15 }, 16 "scripts": { 17 "start": "react-scripts start", 18 "build": "react-scripts build", 19 "test": "react-scripts test --env=jsdom", 20 "eject": "react-scripts eject", 21 }, 22 "devDependencies": { 23 "redux-devtools-extension": "^2.13.2" 24 }, 25 "proxy": "http://localhost:8080" 26 }
然後端項目是放在 backend
這個目錄中,其目錄結構以下:react
1 backend 2 ├── etc 3 ├── node_modules 4 ├── package-lock.json 5 ├── package.json 6 └── server.js
它的 package.json
文件,內容以下:mongodb
1 { 2 "name": "backend", 3 "version": "1.0.0", 4 "description": "", 5 "main": "server.js", 6 "scripts": { 7 "test": "echo \"Error: no test specified\" && exit 1", 8 "start": "nodemon --exec babel-node -- ./server.js" 9 }, 10 "keywords": [], 11 "author": "", 12 "license": "ISC", 13 "dependencies": { 14 "body-parser": "^1.18.2", 15 "express": "^4.16.2", 16 "mongodb": "^3.0.4" 17 }, 18 "devDependencies": { 19 "babel-cli": "^6.26.0", 20 "babel-preset-es2015": "^6.24.1", 21 "nodemon": "^1.17.1" 22 } 23 }
如今前端項目要運行起來簡單,只要運行以下命令便可。express
$ npm run start
就會跑 3000
端口。npm
那麼要運行服務器的程序的話,可能要這樣:json
1 $ cd backend 2 $ npm run start
就會跑 8080 端口。redux
那麼有沒有一種方法同時運行兩個服務呢?後端
就是用一條命令跑兩個服務。服務器
解決方法以下:
一、在項目根目錄下,運行:
1 $ npm i concurrently --save 2 或 3 $ yarn add concurrently
package.json
文件,以下:1 { 2 "name": "crudtest", 3 "version": "0.1.0", 4 "private": true, 5 "dependencies": { 6 "classnames": "^2.2.5", 7 "concurrently": "^3.5.1", 8 "react": "^16.2.0", 9 "react-dom": "^16.2.0", 10 "react-redux": "^5.0.7", 11 "react-router-dom": "^4.2.2", 12 "react-scripts": "1.1.1", 13 "redux": "^3.7.2", 14 "redux-thunk": "^2.2.0" 15 }, 16 "scripts": { 17 "start": "react-scripts start", 18 "build": "react-scripts build", 19 "test": "react-scripts test --env=jsdom", 20 "eject": "react-scripts eject", 21 "server": "npm start --prefix backend", 22 "dev": "concurrently \"npm run server\" \"npm run start\"" 23 }, 24 "devDependencies": { 25 "redux-devtools-extension": "^2.13.2" 26 }, 27 "proxy": "http://localhost:8080" 28 }
主要添加了下面這兩行:
1 "server": "npm start --prefix backend", 2 "dev": "concurrently \"npm run server\" \"npm run start\""
有了 --prefix backend
就不用 cd backend
了,也就是說運行 npm run server
就會跑後端的服務,至關於:
1 $ cd backend 2 $ npm run start
最後運行 npm run dev
至關於同時運行下面兩條命令:
1 $ npm run server 2 $ npm run start
界面以下: