Search code examples
reactjswebpackcode-splittingserver-side-rendering

How to do a code splitting with server side rendering by using require.resolveWeak()?


App/index.js

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

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;
        }
    }
}

I'm using webpack 3.9.1, react 16.0.0.

I'm trying to implement code splitting with SSR. But 'module_ID'-th element from 'require.resolveWeak' is not in __webpack_modules__ array.

Only the element at that index is empty.

Code splitting on the client works well.

I don't know what I misunderstood. I would like an answer. Thank you for reading.


Solution

  • Did you solve the problem that you don't have the async bundles on the client on first render that you used on the server?

    For everyone else who tries to solve this and stumbles on this question. The easiest way to use code-splitting is by using a library like react-loadable (https://github.com/jamiebuilds/react-loadable)

    It comes with convenience methods for rendering loading states, time-outs, SSR methods to track which chunks were loading to you can add them to the page so that they are loaded before you start rendering.