Reputation: 31
I'm going through the exercise of making my webpack bundle smaller, and using webpack's bundle analyzer I saw that a really heavy package is being included in two different async chunks, even though it's only used once. After some digging in my code, I've come to realize that it is probably because of the following scenario:
file1.js
import { foo } from 'ReallyHeavyPackage'
export function a(): string {
console.log("called a()");
}
export function b(): string {
return foo();
}
file2.js
import { a } from './file1.js'
a();
file3.js
import { b } from './file1.js'
b();
I'm assuming that since file1 imports the heavy package globally, and file2 imports a function from file1, it gets the heavy package as a dependency, even though it doesn't import the function that is actually using the package. I'd expect (or rather, wish) that only the chunk for file3 has the heavy dependency included, since it's the only place where it is being used.
Is there a specific way I should be handling an import like this? Perhaps a magic configuration I can do in webpack to help with this, a better way of structuring the modules/functions or just better way to import functions/modules/packages?
I'm using webpack 4 and I'm on ES2017
Upvotes: 3
Views: 65
Reputation: 163
I think what you're looking for is the Webpack CommonChunksPlugin
: https://webpack.js.org/plugins/commons-chunk-plugin/. This plugin takes common chunks (modules/libraries) from different bundles and puts them into their own bundle.
Upvotes: 0
Reputation: 163
Maybe try dynamic imports?
export function a(): string {
console.log("called a()");
}
export async function b(): string {
const { foo } = await import('ReallyHeavyPackage');
return foo();
}
https://webpack.js.org/guides/code-splitting/#dynamic-imports
Upvotes: 1