【问题标题】:Server-side render does not render UI library服务器端渲染不渲染 UI 库
【发布时间】:2019-01-17 23:30:26
【问题描述】:

我正在尝试为我的应用程序实现服务器端渲染。它曾经是使用ReactDom 的客户端渲染。在客户端渲染中一切正常,但是现在当我让它在服务器端渲染时,没有任何 CSS 表和 UI 库(Reactstrap + Material UI)被渲染。用户界面完全崩溃了。

我将我的 App.js(带有所有 UI 的实际前端页面)注入到我的 html.js(模板)中

我的服务器:

import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server'
import App from '../../src/App'
import Html from '../../src/html.js'
const app = express();

// console.log that your server is up and running
app.listen(3001, () => console.log(`Listening on port 3001`));

app.get('/',(req,res) => {
  const title="2FA SDK"
  const body = renderToString(<App/>)
  res.send(
    Html({
      body,
      title,
    })
  )
})

我的 html.js(只是一个简单的模板):

const Html = ({ body, styles, title }) => `
  <!DOCTYPE html>
  <html>
    <head>
      <title>${title}</title>
    </head>
    <body style="margin:0">
      <div id="app">${body}</div>
    </body>
  </html>
`;

我的 app.js(使用材质 ui,最小)

render(){
    return(
        <div className="container">
            <div>
                <TextField 
                    label="Application Name"
                    type="text" 
                    variant="outlined"
                    onChange={this.handleApplicationName}
                />
            </div>
            <div>
                <FormLabel>Phone</FormLabel>
                <div>
                    <OutlinedInput
                        value={this.state.textmaskArray[2]}
                        onChange={(e) => this.handlePhoneNumber(e,2)}
                        labelWidth={200}
                    />
                </div>
            </div>
            <Button variant="contained" color="primary" onClick={this.props.buttonAction}>
            </Button>
        </div>

App.js 中使用 reactstrap 的部分:

render(){
    return(
      <CardControl
        title={"Code Authention"}
        message={"For your security, we need to verify your identity by sending a code to your phone number"}
        >
        <Container>
            <Row>
                <Col>
                    <div>{this.props.phoneList}</div>
                </Col>
                <Col>
                    <div>{this.props.methodList}</div>
                </Col>
            </Row>
            <Button className="sm-2" disabled={this.props.disabled} color="info" onClick={this.props.buttonAction}>{this.props.buttonName}</Button>
        </Container>
      </CardControl>

) } 我的 webpack.config.js:

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const nodeExternals = require("webpack-node-externals");

module.exports = [
    {
        /*Config for backend code*/ 
        entry: './src/server/server.js',
        target: 'node',
        output: {
            filename: 'server.js'
        },
        externals: [nodeExternals()],
        module: {
            rules: [
                {
                    test: /\.(js|jsx)$/,
                    exclude: /node_modules/,
                    use: {
                        loader: "babel-loader"
                    }
                },
                {
                    test: /\.html$/,
                    use: {
                        loader: "html-loader",
                        options: { minimize: true }
                    }
                },
                {
                    test: /\.css$/,
                    use: [MiniCssExtractPlugin.loader,"css-loader"]
                }
            ]
        },
        plugins: [
            new HtmlWebPackPlugin({
                template: "./public/index.html",
                filename:"./index.html"
            }),
            new MiniCssExtractPlugin({
                filename: "[name].css",
                chunkFilename:"[id].css"
            })
        ]
    },
]

我在用什么Create-react-app

我的尝试:我安装了 CSS 加载器,但它根本不起作用。 我还查了material-ui关于服务器端渲染的文档,感觉只是少了一小部分,他们提供的指令可能有点矫枉过正。

我需要什么帮助:我试图弄清楚为什么来自 material-ui 或 bootstrap 的 UI 组件根本没有得到渲染。我怀疑 nodeExternal 将它们排除在外,但我不确定。

【问题讨论】:

  • 你是否在任何地方为你的渲染元素补水?
  • @apokryfos 不,让我发布我的 app.js

标签: javascript reactjs server-side-rendering


【解决方案1】:

您需要在客户端对渲染的 HTML 进行水合,以便让 react 接管。

使用以下命令创建一个 client.js 文件:

import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.hydrate(
  <App/>,
  document.querySelector('#app'),
);

请注意,水合物应与renderToString 呈现的内容相匹配。

接下来将其作为附加条目添加到您的 webpack 配置中:

module.exports = [
{
        /*Config for backend code*/ 
        entry: './src/server/server.js',
        target: 'node',
        output: {
            filename: 'server.js'
        },
        externals: [nodeExternals()],
        module: {
            rules: [
                {
                    test: /\.(js|jsx)$/,
                    exclude: /node_modules/,
                    use: {
                        loader: "babel-loader"
                    }
                },
                {
                    test: /\.html$/,
                    use: {
                        loader: "html-loader",
                        options: { minimize: true }
                    }
                },
                {
                    test: /\.css$/,
                    use: [MiniCssExtractPlugin.loader,"css-loader"]
                }
            ]
        },
        plugins: [
            new HtmlWebPackPlugin({
                template: "./public/index.html",
                filename:"./index.html"
            }),


  new MiniCssExtractPlugin({
            filename: "[name].css",
            chunkFilename:"[id].css"
        })
    ]
},
{ 
   entry: './client.js',
   output: {
      filename: 'bundle.js',
   },
   module: {
      rules: [ {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: 'babel-loader',
      },
   ],
 },
]

更改您的 html 呈现代码以包含以下内容:

const Html = ({ body, styles, title }) => `
  <!DOCTYPE html>
  <html>
    <head>
      <title>${title}</title>
    </head>
    <body style="margin:0">
      <div id="app">${body}</div>
      <script async src="/bundle.js"></script>
    </body>
  </html>
`;

我不是 100% 确信这个确切的代码是否会起作用,但这是一般的想法。

【讨论】:

  • 我应该运行服务器还是应该运行 bundle.js?
  • Webpack 应该创建两个文件。您运行服务器,当它提供 HTML 时,它也应该发送 bundle.js
  • 我正在运行 nito “文档未定义”错误。我认为是因为服务器端渲染没有文档。
  • 服务器端没有document,但client.js只能由客户端加载。 &lt;script async src="/bundle.js"&gt;&lt;/script&gt; 是根据我的理解发送给客户端的标记的一部分。
猜你喜欢
  • 2021-06-18
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2015-05-07
  • 2018-01-05
  • 2013-04-20
  • 1970-01-01
相关资源
最近更新 更多