我正在尝试使用create-react-app项目实现服务器端渲染。我现在不需要路线,因为它是一个单页应用程序。我一直在阅读一些文章,但它们对我来说似乎很复杂。有人可以指导我如何做或者可以将我链接到一些更简单的文章吗?
这是迄今为止的代码: -
主应用程序组件,导入其他组件: -
import React, { Component } from "react";
import HomePage from "./HomePage";
import "./App.css";
class App extends Component {
render() {
return(
<div>
<HomePage/>
</div>
);
}
}
export default App;
Express代码到现在为止: -
import express from "express";
import React from "react";
import { renderToString } from "react-dom/server";
import App from "../src/App";
const app = express();
app.use(express.static("../public"));
app.get('*', (req, res) => {
res.send(`
<!DOCTYPE html>
<head>
<title>Universal React</title>
</head>
<body>
<div id="root">${renderToString(<App/>)}</div>
</body>
</html>
`);
});
app.listen(3000, () => {
console.log('Server running on PORT 3000');
})
我到目前为止检查过的所有文章或视频都使用webpack并对webpack.config.js文件进行了更改,但我使用的是包含webpack的Create-react-app,没有配置文件所以我是一个对如何进行必要的更改感到困惑?
答案 0 :(得分:0)
你必须eject project / scripts / webpack config
这是关于如何使用react-router / redux实现服务器端渲染的example article
答案 1 :(得分:0)
react-scripts
替换为react-app-tools
package.json
中的NPM脚本以致电react-app build
,react-app start
src/index.js
重命名为src/app.browser.js
,为服务器添加一个入口点src/app.node.js
.
├── /build/ # Compiled output
│ ├── /public/ # Pre-compiled client-side app
│ └── server.js # Pre-compiled Node.js app
├── /src/ # Application source files
│ ├── /components/ # React.js components
│ │ ├── /App/ # - The top-level React component
│ │ ├── /Button/ # - Some other UI element
│ │ └── ... # - etc.
│ ├── app.browser.js # Client-side rendering, e.g. ReactDOM.render(<App />, container)
│ ├── app.node.js # Server-side rendering, e.g. ReactDOMServer.renderToString(<App />)
│ └── server.js # Server-side entiry point, e.g. app.listen(process.env.PORT)
└── package.json # List of project dependencies and NPM scripts
src/app.browser.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
ReactDOM.hydrate(<App />, document.getElementById('root'));
src/app.node.js
import path from 'path';
import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import App from './components/App';
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('*', (req, res) => {
res.send(ReactDOMServer.renderToString(<App />));
});
export default app;
package.json
{
"dependencies": {
"express": "^4.6.12",
"react": "^16.2.0",
"react-dom": "^16.2.0"
},
{
"react-app-tools": "^2.0.0-beta.5"
},
"scripts": {
"test": "react-app test --env=jsdom",
"build": "react-app build",
"start": "react-app start"
}
}