Usage

Webpack Plugin

First we need to import the package into our component;

const ReactLoadableSSRAddon = require('react-loadable-ssr-addon');

module.exports = {
  entry: {
    // ...
  },
  output: {
    // ...
  },
  module: {
    // ...
  },
  plugins: [
    new ReactLoadableSSRAddon({
      filename: 'assets-manifest.json',
    }),
  ],
};

HTTP Server

// import `getBundles` to map required modules and its dependencies
import { getBundles } from 'react-loadable-ssr-addon';
// then import the assets manifest file generated by the Webpack Plugin
import manifest from './your-output-folder/assets-manifest.json';

...

// react-loadable ssr implementation
const modules = new Set();

const html = ReactDOMServer.renderToString(
<Loadable.Capture report={moduleName => modules.add(moduleName)}>
  <App />
</Loadable.Capture>
);

...

// now we concatenate the loaded `modules` from react-loadable `Loadable.Capture` method
// with our application entry point
const modulesToBeLoaded = [...manifest.entrypoints, ...Array.from(modules)];
// also if you find your project still fetching the files after the placement
// maybe a good idea to switch the order from the implementation above to
// const modulesToBeLoaded = [...Array.from(modules), ...manifest.entrypoints];
// see the issue #6 regarding this thread
// https://github.com/themgoncalves/react-loadable-ssr-addon/issues/6

// after that, we pass the required modules to `getBundles` map it.
// `getBundles` will return all the required assets, group by `file type`.
const bundles = getBundles(manifest, modulesToBeLoaded);

// so it's easy to implement it
const styles = bundles.css || [];
const scripts = bundles.js || [];

res.send(`
  <!doctype html>
  <html lang="en">
    <head>...</head>
    ${styles.map(style => {
      return `<link href="/dist/${style.file}" rel="stylesheet" />`;
    }).join('\n')}
    <body>
      <div id="app">${html}</div>
      ${scripts.map(script => {
        return `<script src="/dist/${script.file}"></script>`
      }).join('\n')}
  </html>
`);

See how easy to implement it is?

Last updated