Search code examples
reactjswebpackecmascript-6importcode-splitting

How to dynamically switch code splitting on/off


We have a ReactJS app that we bundle with webpack. We use React-Loadable to help us with code splitting and right now our app's router module looks like

import Loadable from 'react-loadable'

const LoadableComponent = (url, component)=>Loadable({
    loader:()=> import(`${url}`),
    loading: ()=><div></div>,
    render(loaded, props){
        let LoadedComponent = loaded[component]
        return <LoadedComponent {...props}/>
    }
})

const Landing = LoadableComponent('./components/LandingPage', 'Landing')
// ... all the other imports have this form ^

That being said, during development, code splitting seems to slow down webpack --watch and can make debugging in browser be a bit more of a pain (we don't use sourcemaps because they haven't worked great for us in the past).

I'm trying to figure out a way to dynamically switch code-splitting on or off. My idea is to make LoadableComponent act like a normal import when code-splitting is off. However, both import and react-loadable seem a bit too mystical for it to be straightforward, I haven't been able to find a way to do that in javascript.


Solution

  • What you could try and this will depend on your webpack implementation but if you have a development webpack.config ie webpack.config.dev.js you could add to the plugins array:

    new webpack.optimize.LimitChunkCountPlugin({
      maxChunks: 1
    })
    

    This will stop the code splitting and only builds one file. In my tests so far react-loadable seems to be cool with this and just work as per normal with out the code splitting.

    If you wanted a way to switch this on and off dynamically you could pass a command line argument to webpack when you start it up and then conditionally add the above code. At the bottom of your webpack config file.

    if (yourArgHere) {
      module.exports.plugins.push(
        new webpack.optimize.LimitChunkCountPlugin({
          maxChunks: 1
        })
      );
    }