最近全權負責了一個前後端分離的web專案,前端使用create-react-app, 後端使用golang做的api服務。
npx create-react-app my-app
cd my-app
npm start
歘歘歘,就搭建了一個react前端專案。
前端老鳥都知道npm start
或yarn start
以開發模式啟動react App:在localhost:3000除錯預覽前端專案,編輯器的變更會實時體現在web頁面。
前端老鳥也知道npm run build
或yarn build
是以生產為目標,將優化後的靜態檔案輸出到build
資料夾 (優化構建效能、壓縮產出物、給檔名雜湊)。
從一個全棧程式設計師的視角,開發時最好能一次啟動前後端兩個程式。
大前端快閃二: 你能在react app開發模式中一鍵啟動多個服務嗎?
1. 安裝concurrently外掛
npm install concurrently -D
2. 配置npm命令
"scripts": {
"start": "concurrently \"react-scripts start\" \"go run main.go\" ",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
},
注意上面的start
指令碼內容:
react-scripts start
啟動了前端app,
go run main.go
啟動了後端api服務。
3. npm start
或yarn start
啟動專案
在開發模式,前後端專案不在一個埠,存在跨域。
解決跨域問題,要麼反向代理,要麼讓後端做CORS。
這裡我們採用反向代理的方式。
4. react開發模式設定proxy
create-react-app允許你設定一個代理URL,僅用於開發模式。
To tell the development server to proxy any unknown requests to your API server in development, add a proxy field to your package.json。
在package.json檔案中,新增proxy:"localhost:8034"
,開發模式localhost:3000收到的未知請求將會由前端開發伺服器代理轉發。