[英]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.