[英]How do I build react and node together?
我遇到了一個小問題。 我知道我可以使用npm run build
來構建 react-app,它將創建優化的構建文件夾,我可以將其加載到生產環境中。 但是幾天前,我開始在我的react
應用程序中使用node.js
。 我現在很困惑 - 我現在應該如何構建這樣的應用程序?
我的文件夾結構:
my-app-|
|-client-|
| |-package.json // root react package file
|
|
|- server.js // node.js (express) root file
|- package.json // root node package file
編輯 1
> server@1.0.0 build C:\Users\Horseman.mini\PhpstormProjects\landing
> npm run build && cd ./client && npm run build
> server@1.0.0 build C:\Users\Horseman.mini\PhpstormProjects\landing
> npm run build && cd ./client && npm run build
> server@1.0.0 build C:\Users\Horseman.mini\PhpstormProjects\landing
> npm run build && cd ./client && npm run build
> server@1.0.0 build C:\Users\Horseman.mini\PhpstormProjects\landing
> npm run build && cd ./client && npm run build
'npm' is not recognized as internal or external command, operable program or batch file
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! server@1.0.0 build: `npm run build && cd ./client && npm run build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the server@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Horseman.mini\AppData\Roaming\npm-cache\_logs\2021-02-22T14_49_23_308Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! server@1.0.0 build: `npm run build && cd ./client && npm run build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the server@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Horseman.mini\AppData\Roaming\npm-cache\_logs\2021-02-22T14_49_23_345Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! server@1.0.0 build: `npm run build && cd ./client && npm run build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the server@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
PS npm --version
返回6.14.10
如果我 go 到客戶端文件夾並構建它將構建,但沒有服務器端
您現在可以將提供前端構建文件夾的責任委托給server.js
,即僅服務器。 最簡單的事情可能是使用express.static
像這樣為前端提供服務:-
app.use(express.static(path.join(__dirname, "./dist")));
其中app
是您的express
服務器的實例。
其中./dist
是根文件夾的相對路徑,因此類似於my-app/dist
放置構建文件的位置。 同樣,您要使用什么名稱完全取決於您。 基本上所有 static 文件,即js、css 和 html都將成為此dist
文件夾的一部分,並將在用戶點擊基本路徑時提供給用戶。 由於前端和后端都可從同一服務器獲得,因此無需處理CORS場景,除非您的實現絕對需要它。
將父文件夾與package.json
一起使用,並將您各自的構建命令放入其中。
my-app-|
|-client-|
| |-package.json // root react package file
|
|
|- server.js // node.js (express) root file
|- package.json // root node package file ---> add build command for front and back here.
您的根package.json
可以具有以下命令。
{
"build": "npm run build && cd ./client && npm run build"
}
這將首先構建您的后端,然后構建前端,如果您希望兩個命令同時運行,那么您可以同時使用package 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.