How To Avoid Duplicate Code in Chunks Using CRA + Code Splitting
Asked Answered
A

0

6

For example, say we have two components with a common import:

...
        
import Hello from './Hello'
        
class A extends Component {}

and

...
    
import Hello from './Hello'
    
class B extends Component {}

Those components are then loaded asynchronously in another component, like this:

...
    
import Loadable from 'react-loadable'
    
const AsyncA = Loadable({
    loader: () => import(/* webpackChunkName: "A" */ "./A"),
    loading: () => <div>Generic Loading Message</div>
});

const AsyncB = Loadable({
    loader: () => import(/* webpackChunkName: "B" */ "./B"),
    loading: () => <div>Generic Loading Message</div>
});

Both the "A" and "B" chunks will contain the "Hello" code, delivering duplicated code to the browser.

In my research, I've determined this won't happen if "Hello" is imported in any other component that isn't asynchronously loaded. In that case, it is bundled into the "main" chunk, instead of the "A" and "B" chunks.

While that's an option, it leaves much to be desired. This guide demonstrates how to configure webpack to create a "common" module, which seems ideal because it doesn't require any code restructuring to achieve the desired effect.

However, the webpack configs are off limits with CRA.

Are there any better solutions here?

Altar answered 29/12, 2018 at 0:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.