How Module Import Style Affects Bundle Size

Aug 25, 2024 · 1 min read · 195 Words · -Views -Comments

We recently discussed the impact of module import styles on bundle size in an internal CR. I think this is quite important, so I’m marking it down here.

Taking a component library as an example, you’ll see lib and es folders in the package. In development, we need to pay attention to how we import modules—different import styles can cause huge differences in bundle size.

Example

Let’s start with an example. The screenshot below shows that importing from the es directory and importing from the package root have the same bundle size, but importing from lib is very different.

https://static.1991421.cn/2024/2024-08-25-224824.jpeg

Analysis

  1. Webpack has tree-shaking. When JavaScript uses ES module syntax and is built in production mode, tree-shaking is enabled.

  2. For the component library mentioned above, when we use es imports, it enables tree-shaking. Tools like Webpack will then perform on-demand bundling instead of full bundling.

  3. The package.json of the component library shows both main and module fields declared:

      "main": "lib/index.js",
      "module": "es/index.js",
    

Final Thoughts

Frontend bundle size has always been an important issue, with solutions like CDN, on-demand loading, on-demand bundling, and GZIP. The import style issue discussed above is just one aspect of this problem.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover