简体   繁体   English

React SSR 替代方案

[英]React SSR alternatives

I am currently working on a project that someone else built and I was asked to implement server side rendering, it's a huge project and it uses a custom routing system based on a "builder JSON" taken by a main component that selects which components to render based on the route, it is meant to keep the app dynamic and to adjust to the needs of several customers.我目前正在处理一个其他人构建的项目,我被要求实现服务器端渲染,这是一个巨大的项目,它使用基于“构建器 JSON”的自定义路由系统,该主组件选择要渲染的组件基于路线,它旨在保持应用程序动态并适应多个客户的需求。

I have been checking everywhere trying to find an answer but im new to SSR and it's a big challenge.我一直在到处寻找答案,但我对 SSR 很陌生,这是一个很大的挑战。

I am currently testing an approach using express that looks like this:我目前正在测试一种使用 express 的方法,如下所示:

import 'babel-polyfill';
import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { StaticRouter } from 'react-router';
import bodyParser from 'body-parser';

import { App } from '../src/App';

const app = express();
const PORT = process.env.PORT || 8000;

app.use(bodyParser.json());
app.use(express.static('ssrBuild'))

app.get('*', (req, res) => {
    const context = {}
    const content = ReactDOMServer.renderToString(
        <StaticRouter location={req.url} context={context}>
            <App />
        </StaticRouter>
    );

    const html = `
    <html>
        <head>
        </head>
        <body>
            <div id="root">
                ${content}
            </div>
        </body>
    </html>
    `;
    res.send(html);
});

app.listen(PORT, () => {
    console.log(`App running on port ${PORT}`);
});

The problem I am currently having is that the App component calls the "complex routing component" from another repository in the node_modules (also build by them), my webpack config is taking the App component and finding jsx, which cant obviouly be run in the server.我目前遇到的问题是 App 组件从 node_modules 中的另一个存储库调用“复杂路由组件”(也由它们构建),我的 webpack 配置正在使用 App 组件并找到 jsx,这显然不能在服务器。

Webpack config: Webpack 配置:

const path = require('path');
const webpackNodeExternals = require('webpack-node-externals');

module.exports = {
    target: 'node',
    entry: {
        server: './ssr/server.js',
        
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, '..', 'ssrBuild'),
        publicPath: '/ssrBuild'
    },
    module: {
        rules: [
            {
                test: /\js$/,
                loader: 'babel-loader',
                exclude: '/node_modules/',
                options: {
                    presets: [
                        '@babel/react',
                        ['@babel/preset-env', {
                            targets: { browsers: ['last 2 versions'] }
                        }]
                    ],
                    plugins: [
                        ['@babel/plugin-proposal-decorators', { 'legacy': true }],
                        '@babel/plugin-proposal-class-properties',
                        '@babel/plugin-syntax-function-bind',
                        '@babel/plugin-transform-async-to-generator',
                        '@babel/plugin-proposal-export-default-from',
                        'babel-plugin-jsx-control-statements',
                        'react-hot-loader/babel',
                        'lodash',
                    ]
                }
            }
        ]
    },
    externals: [webpackNodeExternals()]
}

Is there a way I can tell webpack to transpile the jsx in the node_modules folder "on the go"?有没有办法告诉 webpack “随时随地”转换 node_modules 文件夹中的 jsx? What other solutions could there be?还有什么其他的解决方案?

Also, the whole point of this project is to impprove the SEO for these apps, I would only need to SSR the index page and any direct link to content in it.此外,这个项目的重点是改进这些应用程序的 SEO,我只需要 SSR 索引页面和指向其中内容的任何直接链接。 No need to SSR the entire app is there a way this can be achieved?不需要对整个应用程序进行 SSR 有没有办法可以实现?

I was also wondering if refactoring the entire app to use Next.js would be worth it if this were possible only for the index page and any direct link.我还想知道如果仅对索引页面和任何直接链接可行,那么重构整个应用程序以使用 Next.js 是否值得。

Thank you in advance!先感谢您!

If the team can afford it then you should definitely go and try a framework.如果团队负担得起,那么您绝对应该 go 并尝试一个框架。 This will me more maintainable on the long term.从长远来看,这将使我更易于维护。 I would recommend you try Next.js over Gatsby, Both are great options but in my opinion Next has two or three advantages like Incremental Static Regeneration (Regenerate if your content change continuously) or you can choose between use Server Sider or Static generation based on your routes.我建议您在 Gatsby 上尝试 Next.js,两者都是不错的选择,但在我看来 Next 有两个或三个优点,例如增量 Static 再生(如果您的内容不断变化,则重新生成)或者您可以根据您的服务器 Sider 或 Z84A8921B275FDB407 生成路由进行选择. You can use SSR on your dashboard and SSG on your home and landing pages for example.例如,您可以在仪表板上使用 SSR,在主页和登录页面上使用 SSG。

If you don't need any type of pre-rendering you can go for client-side only and even then Next are gonna make a couple of optimization that will speed up your site.如果您不需要任何类型的预渲染,您可以 go 仅用于客户端,即使这样,Next 也会进行一些优化以加速您的网站。

On the long term it will save you a lot of time and it will be easy to maintain从长远来看,它将为您节省大量时间,并且易于维护

If you want to skip the app refactoring to implement it into existent SSR frameworks such as Gatsby or NextJs, you could try with this:如果您想跳过应用程序重构以将其实现到现有的 SSR 框架(例如 Gatsby 或 NextJs)中,您可以尝试以下操作:

https://github.com/jonamat/pure-react-ssr-hmr https://github.com/jonamat/pure-react-ssr-hmr

It's a preconfigured template to developing React SSR apps with HMR support specifically optimized to speed up your development workflow.它是一个预配置的模板,用于开发具有 HMR 支持的 React SSR 应用程序,专门优化以加快您的开发工作流程。 It includes an open webpack configuration for both front and back end, a ready express app, linter, SCSS support and a configuration file to manage the build and app behavior.它包括用于前端和后端的开放式 webpack 配置、现成的 express 应用程序、linter、SCSS 支持以及用于管理构建和应用程序行为的配置文件。

You need just to put your app wrapper into the /common folder.您只需将应用程序包装器放入 /common 文件夹即可。 After that you can deploy your server.js and the static resources into your target machine and run it.之后,您可以将 server.js 和 static 资源部署到目标机器并运行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM