为什么当我 运行 nodejs 服务器以 React 应用程序作为前端时没有物理 client/build 文件夹

Why there is no physical client/build folder when i run nodejs server with react app as frontend

我正在使用 esausilva/example-create-react-app-express 为我的 MERN 项目创建基础

~/server.js 文件中写入

if (process.env.NODE_ENV === 'production') {
  // Serve any static files
  app.use(express.static(path.join(__dirname, 'client/build')));

  // Handle React routing, return all requests to React app
  app.get('*', function(req, res) {
    res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
  });
}

据我了解,这意味着如果 express 服务器 运行ning 处于生产模式,那么它将查看 client/build 文件夹以提供静态文件(即前端代码)和服务器将发送 client/build/index.html 文件的任何路由请求。

package.json 我有以下 npm run 命令

"scripts": {
    "client": "cd client && yarn start",
    "server": "nodemon server.js",
    "dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\"",
    "dev:server": "cd client && yarn build && cd .. && yarn start",
    "start": "node server.js",
    "heroku-postbuild": "cd client && npm install && npm install --only=dev --no-shrinkwrap && npm run build"
  },

我的困惑是当我 运行 yarn dev 它 运行 服务器和反应应用程序同时发生(一切都很完美)但是在客户端文件夹中我没有​​看到任何物理构建文件夹,为什么会这样,如果不先创建构建文件夹,Express 服务器如何理解要提供哪个文件。

您需要一个构建脚本,以便它可以生成构建文件夹,命令 yarn dev 的作用是运行开发服务器。您可以在 React 文档中查看更多信息。

在客户端reactJS package.json文件中,添加

"build": "react-scripts build"

到脚本并进入客户端文件夹,然后 运行

npm run build

这将创建 Build 文件夹。每次要更新构建文件夹时都必须 运行 此命令。

我想我已经弄清楚为什么我的本地 machine.The 中没有物理 client/build 文件夹,原因是当我 运行 yarn dev 它输出以下日志

$ concurrently --kill-others-on-fail "yarn server" "yarn client"
$ nodemon server.js
$ cd client && yarn start
[0] [nodemon] 2.0.6
[0] [nodemon] to restart at any time, enter `rs`
[0] [nodemon] watching path(s): *.*
[0] [nodemon] watching extensions: js,mjs,json
[0] [nodemon] starting `node server.js`
$ react-scripts start
[0] Listening on port 5000
[0] Database Connected
[1] ℹ 「wds」: Project is running at http://192.168.0.10/
[1] ℹ 「wds」: webpack output is served from 
[1] ℹ 「wds」: Content not from webpack is served from /home/mirsahib/Desktop/MERN_WS/Super-MERN-User-Authentication/client/public
[1] ℹ 「wds」: 404s will fallback to /
[1] Starting the development server...
[1] 
[1] Browserslist: caniuse-lite is outdated. Please run:
[1] npx browserslist@latest --update-db
[1] Compiled successfully!
[1] 
[1] You can now view create-react-app-express in the browser.
[1] 
[1]   Local:            http://localhost:3000
[1]   On Your Network:  http://192.168.0.10:3000
[1] 
[1] Note that the development build is not optimized.
[1] To create a production build, use yarn build.
[1] 

第三行 yarn 运行 $ cd client && yarn start 这意味着它将进入客户端文件夹 运行 client/package.json 脚本 tag.This 是当我们使用 create-react-app 命令创建一个普通的 React 应用程序时发生的情况,我们没有在其中看到任何 /build 文件夹 app.The build 文件夹仅在应用程序处于生产模式时创建(例如: heroku) 不在开发中 mode.That 是没有物理 client/build 文件夹的原因。