Single import from an index file vs multiple single imports - Effects on Performance?
Asked Answered
F

1

6

Background

I'm using Gatsby to build a blog, and I'm trying to improve performance. I also want to implement code-splitting and lazy loading.

2 Ways of importing components

Let's say I have to import 2 components that are in the same folder; there are two ways to do this:

Way 1: Group all the components in an index.ts file

import { Component1, Component2 } from '../components/index.ts'

Way 2: Import the single components referencing the specific path

import { Component1 } from '../components/Component1'
import { Component2 } from '../components/Component2'

Question

The first way looks better and is faster to code, but what are its effects on performance?

From what I read in the Gatsby Documentation, the second approach should be preferred, because otherwise Webpack will bundle and import also other components that you don't actually need, thus increasing the size of the bundle (and negatively effecting performance).

Should I then convert all my grouped imports into specific imports, and remove the index.ts files?

Fucoid answered 15/7, 2022 at 12:7 Comment(1)
From hardware point, 1 big chunk read looks better than 2 small chunks read. Unless small chunks are on different disk drives for simultaneous reading. I am guessing Javascript's engine can do simultaneous reading by overlapping i/o automatically.Haftarah
F
0

If you use an up-to-date webpack version, then the tree shaking feature will minimize what is imported into the generated bundle for either way you described.

In the link you gave, it is specifically referring to Gatsby v2, so I'm assuming that it no longer holds for v3 and up.

Floridafloridia answered 15/7, 2022 at 13:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.