最近全權負責了一個前后端分離的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收到的未知請求將會由前端開發服務器代理轉發。