1

I am attempting to do some code-splitting in my create-react-app application that utilizes server side rendering.

I am utilizing 'react-loadable` to do the code-splitting: https://github.com/thejameskyle/react-loadable

As of now I simply have split my Home.js component away from the rest of my app, just to see if it works. In development mode (read: not SSR), it's chunked off and works fine.

However, I can't get things to work on the server. I'm following the guide on their Github page and am stuck because of the webpack changes needed. In create-react-app applications, you don't have access to webpack as it's hidden away.

The error I receive when starting the server is:

return (0, _importInspector.report)(import('../components/home/Home'), {
                                                ^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10) ...

I'm pretty sure it's because I don't have webpack configured correctly as stated in the guide.

In the guide, it clearly states for SSR:

First we need Webpack to tell us which bundles each module lives inside. For this there is the React Loadable Webpack plugin.

Import the ReactLoadablePlugin from react-loadable/webpack and include it in your webpack config. Pass it a filename for where to store the JSON data about our bundles.

// webpack.config.js
import { ReactLoadablePlugin } from 'react-loadable/webpack';

export default {
    plugins: [
        new ReactLoadablePlugin({
            filename: './dist/react-loadable.json',
        }),
    ],
};

I don't think this is possible without ejecting. Anyone have any idea if react-loadable can be used in a create-react-app server-side-rendered application?

Community
  • 1
  • 1
Gurnzbot
  • 3,742
  • 7
  • 36
  • 55

1 Answers1

2

import these modules at the top of your server file

require('ignore-styles');
require('babel-polyfill')
require('babel-register')({
    ignore: [ /(node_modules)/ ],
    presets: ['es2015', 'react-app'],
    plugins: [
        'syntax-dynamic-import',
        'dynamic-import-node',
        'react-loadable/babel'
    ]
});
Fadi Quader
  • 143
  • 1
  • 8
  • 1
    Nice! The problem is that "dynamic-import-node" will make import() working on server but will cancel code splitting for browser. So we need to enable it for server only (DON'T add it to .babelrc) and this is a perfect place to do that. This answer should be accepted. – Viacheslav Feb 14 '18 at 10:50
  • i have the same question but instead i'm using loadable/components and i get the feeling that it's not splitting correctly because of performance issues. – zahra shahrouzi Feb 25 '21 at 12:08