如何将 SSR 添加到 Express.js 中现有的 React.js 应用程序

How to add SSR to existing React.js application in Express.js

我有一个简单的 React 应用程序,我想在 Express.js 中添加 SSR。

我一开始犯了一个错误,在我的存储库中我只有一个前端文件夹,里面有整个 React 应用程序,其中配置了 typescript、babel 和 webpack。

我还没有玩过SSR,所以我很好奇,如果我想制作这样一个服务器并将其文件放在前端文件夹旁边的文件夹中,我是否必须安装并设置所有我在`frontend 文件夹中创建的依赖项,然后才创建 server.js 文件 ?

然后在“frontend/src”中间我会有 2 个文件 - index.tsx(使用 React.render() 方法),因为我希望能够 运行 应用程序也没有服务器。第二个文件是 indexServer.tsx 和 React.hydrate() 方法,它将转到 server.js 文件(即用于由服务器生成应用程序)。这个概念对吗?

Link 到我的 github 回购与这个反应应用程序:https://github.com/poldeeek/spider-game

If I want to make such a server and have its file in the folder next to the frontend folder, would I have to install and set all the dependencies I made inside the`frontend folder, and only then create the server.js file ?

如果您选择像这样设置两个单独的文件夹,您可能需要重新安装所有依赖项。我建议将 server.js 放在 frontend/server 中,这样就可以使用与 frontend/src/index.js 相同的 node_modules

Then in the middle of "frontend/src" I would have 2 files - index.tsx (with React.render() method), because I would like to be able to run the application also without the server. And 2nd file would be indexServer.tsx with React.hydrate() method, which would go to server.js file (i.e. would be for generating application by server). Is this concept right ?

这里没有正确或错误的答案。如果此设置适合您的需要,请使用它。此设置的唯一挑战是您必须配置 babel 和 webpack 以指向两个不同的文件:index.tsx(如果您不想要服务器)和 indexServer.tsx(如果您想要包括服务器)。