首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用require.resolveWeak()进行服务器端渲染的代码拆分?

如何使用require.resolveWeak()进行服务器端渲染的代码拆分?
EN

Stack Overflow用户
提问于 2018-02-09 20:58:52
回答 1查看 639关注 0票数 0

App/index.js

代码语言:javascript
复制
import React from 'react';
import { with_code_splitting } from 'components/App/Code_splitting/HOC';

export default class App extends React.PureComponent {
    render () {
        return <Child/>;
    }
}

const Child = with_code_splitting({ dynamic:() => import('components/App/Child'), static:() => require.resolveWeak('components/App/Child') });

App/Code_splitting/HOC.js

代码语言:javascript
复制
import React from 'react';

export function with_code_splitting (options) {
    return class Decorated_component extends React.Component {
        static component = null;

        state = { component:Decorated_component.component };

        componentWillMount() {
            if (!this.state.component) {
                if (process.env.NODE_ENV !== 'server_side_rendering') {
                    options.dynamic()
                    .then(({ default:component }) => {
                        Decorated_component.component = component;
                        this.setState({ component });
                    });
                }
                else { // for server-side-rendering
                    const module_ID = options.static();
                    console.log(__webpack_modules__[module_ID]); // undefined
                    this.setState({ component:__webpack_require__(module_ID) });
                }
            }
        }

        render() {
            if (this.state.component) return <this.state.component {...this.props} />
            else return null;
        }
    }
}

我使用的是webpack 3.9.1,react 16.0.0。

我正在尝试使用SSR实现代码拆分。但“require.resolveWeak”中的“module_ID”不在__webpack_modules__数组中。

只有该索引处的元素为空。

客户机上的代码拆分效果很好。

我不知道我误解了什么。我想要一个答案。感谢您的阅读。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-15 16:51:28

您是否解决了在客户端首次渲染时没有在服务器上使用的异步包的问题?

对于其他试图解决这个问题并在这个问题上遇到困难的人。使用代码拆分的最简单方法是使用像react-loadable (https://github.com/jamiebuilds/react-loadable)这样的库

它提供了方便的方法来渲染加载状态,超时,跟踪加载到哪些块的SSR方法,您可以将它们添加到页面,以便在开始渲染之前加载它们。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48706441

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档