前言
對於一些剛跨入全端領域的新手來說,可能會發生以下情形:
這是我的 project 目錄,有前端 client 以及 後端 server 的部分
在我還沒學會使用 package 中的 scripts 時我可能會這麼分別去啟動項目:
// cmd 1 cd server nodemon app.js // cmd2 cd client npm start
雖然這樣也不是不行,但是若你需要同時啟用更多程序的時候就會一直一直的去開終端,這邊介紹一個更便捷的方法。
修改 Scripts
專案根目錄
在 project 根目錄下輸入指令:
npm init -y
接著根目錄底下就會產生 package.json
。
內容如下:
{ "name": "project", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", }
我們可以在 scripts 中使用 cmd 指令,就可以利用 scripts 的部分讓它同時啟動 server 和 client:
"scripts": { "client": "cd client && npm start", "server": "cd server && npm start", "start": "concurrently - kill-others \"npm run server\" \"npm run client\"", "test": "echo \"Error: no test specified\" && exit 1" },
大概的意思就是同時去跑 client 和 server 這兩條指令,而兩條指令分別啟動 client 和 server。
Client
如果你的 client 是用 create-react-app 建的,那 package.json
中應該會有 start
的指令,如果沒有請自己加上:
"scripts": { "start": "react-scripts start", },
並且記得安裝 react-scripts
:
npm i react-scripts --save
Server
server 端的話自己在 package.json
中加上:
"scripts": { "start": "nodemon app.js" }
接著回到 project 根目錄底下輸入指令 npm start
就可以同時開啟 server 和 client 了。
Latest posts by pluto (see all)
- React 那些好看、有趣、實用的函式庫、組件庫推薦(2) - 2022 年 6 月 26 日
- 解決 preact 資源請求路徑錯誤的問題 - 2022 年 6 月 24 日
- [楓之谷私服] 潮流轉蛋機 NPC 腳本優化 - 2022 年 6 月 19 日