世界上最伟大的投资就是投资自己的教育
使用 concurrently 并行地运行多个命令(同时跑前端和后端的服务)
随风发布于4218 次阅读
我现在有一个项目是这样的,前端是用 React 写的,后端是用 Nodejs,目录结构如下:
.
├── README.md
├── backend
├── node_modules
├── package.json
├── public
├── src
└── yarn.lock
这个 package.json
的内容如下:
{
"name": "crudtest",
"version": "0.1.0",
"private": true,
"dependencies": {
"classnames": "^2.2.5",
"concurrently": "^3.5.1",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-redux": "^5.0.7",
"react-router-dom": "^4.2.2",
"react-scripts": "1.1.1",
"redux": "^3.7.2",
"redux-thunk": "^2.2.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
},
"devDependencies": {
"redux-devtools-extension": "^2.13.2"
},
"proxy": "http://localhost:8080"
}
而后端项目是放在 backend
这个目录中,其目录结构如下:
backend
├── etc
├── node_modules
├── package-lock.json
├── package.json
└── server.js
它的 package.json
文件,内容如下:
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon --exec babel-node -- ./server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.2",
"express": "^4.16.2",
"mongodb": "^3.0.4"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"nodemon": "^1.17.1"
}
}
现在前端项目要运行起来简单,只要运行如下命令即可。
$ npm run start
就会跑 3000
端口。
那么要运行服务器的程序的话,可能要这样:
$ cd backend
$ npm run start
就会跑 8080 端口。
那么有没有一种方法同时运行两个服务呢?
就是用一条命令跑两个服务。
解决方法如下:
1、在项目根目录下,运行:
$ npm i concurrently --save
或
$ yarn add concurrently
- 然后更改
package.json
文件,如下:
{
"name": "crudtest",
"version": "0.1.0",
"private": true,
"dependencies": {
"classnames": "^2.2.5",
"concurrently": "^3.5.1",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-redux": "^5.0.7",
"react-router-dom": "^4.2.2",
"react-scripts": "1.1.1",
"redux": "^3.7.2",
"redux-thunk": "^2.2.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"server": "npm start --prefix backend",
"dev": "concurrently \"npm run server\" \"npm run start\""
},
"devDependencies": {
"redux-devtools-extension": "^2.13.2"
},
"proxy": "http://localhost:8080"
}
主要添加了下面这两行:
"server": "npm start --prefix backend",
"dev": "concurrently \"npm run server\" \"npm run start\""
有了 --prefix backend
就不用 cd backend
了,也就是说运行 npm run server
就会跑后端的服务,相当于:
$ cd backend
$ npm run start
最后运行 npm run dev
相当于同时运行下面两条命令:
$ npm run server
$ npm run start
界面如下:
完结。
类似的工具:
本站文章均为原创内容,如需转载请注明出处,谢谢。
0 条回复
暂无回复~~
© 汕尾市求知科技有限公司 | Rails365 Gitlab | 知乎 | b 站 | csdn
粤公网安备 44152102000088号 | 粤ICP备19038915号
Top