olegzhermal
olegzhermal

Reputation: 859

How does importing entire modules affects performance and bundle size?

Describing a question in the simple example

Let's have file A which has 2 named exports:

//FileA.js
export function1(){}
export function2(){}

Let's compare 3 case:

Case 1:

//FileB.js:
import { function1 } from './A'
function1()

//FileC.js:
import { function2 } from './A'
function2()

Case 2:

//FileB.js:
import * as f from './A'
f.function1()

//FileC.js:
import * as f from './A'
f.function2()

Case 3: File A exports an named object containing the function:

//FileA.js
export const f = {
  function1: () => {},
  function2: () => {}
}

//FileB.js:
import { f } from './A'
f.function1()

//FileC.js:
import { f } from './A'
f.function2()

The question is which case is more effective memory- and performance-wise considering bundling those modules with Webpack (and explanation why would be also great – because it looks like in the resulting bundle there should be all the same functions...)?

It's obvious that in this simple case performance is almost the same (it's given just for the simple illustration).

Upvotes: 1

Views: 1607

Answers (1)

David
David

Reputation: 948

In all your cases above, FileB.js and FileC.js will import the whole FileA.js. This is, because function1 and function2 are both defined in 1 single file. As soon as you import one of them, you will load the whole file FileA.js.

How can you make this more efficient? Let's say, FileB.js is loaded initially with your landing page. FileC.js is needed on another page and will be loaded at a later point.

Currently, you would load FileA.js and FileB.js completely.

Because FileB.js is only using function1, you can create a separate file, that contains only this function:

//FileA_1.js
export default function1(){}

//FileB.js:
import function1 from './A_1'
function1()

Now you only load the function definition of function1 and FileB.js. So you reduced the initially loaded bundle by the definition of function2.

Upvotes: 2

Related Questions