Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack including unused exports in final bundle (not tree shaking)

I have a setup where a library's index.js (main entry point) exports everything in the lib... so its setup like this:

export * from "./mod1"
export * from "./mod2"
// etc...

(take a look)

When I import 1 of the exported libraries from that entry point, looks like Webpack is not able to tree-shake the output. running webpack -p is actually including the entire library in the bundle, although only one export was imported. Runing webpack (non-production bundle) does show unused harmony export .... throughout the file (167 times), but why are they not being dropped?

I have a test setup showing this problem here: https://github.com/purtuga/webpack-bundle-test

Hoping someone (smarter than me :) ) can help identify what I am doing wrong.

/Paul

like image 523
Paul T. Avatar asked Oct 17 '22 23:10

Paul T.


1 Answers

I cloned your "webpack-bundle-test" and here is what i did.

  1. Copied "common-micro-libs" src folder from https://github.com/purtuga/common-micro-libs.
  2. Edited the code in mod3.js to: import { objectExtend } from "./common-micro-libs" export default mod3 = objectExtend({}, { text: "module 3" });

  3. I ran webpack locally and found 167 "unused harmony" comments.

  4. With webpack -p i got the following results: enter image description here
  5. Changed code in mod3.js to import objectExtend from "./common-micro-libs/jsutils/objectExtend.js" export default mod3 = objectExtend({}, { text: "module 3" });.
  6. With the above change i could see the following reduction in bundle sizeenter image description here

I believe when importing dependencies, it is better to import only the necessary function/component from the library and this will be packed more effectively in the bundle. I am not able to expalin why so, though i followed the same principle in importing utilities in my project when using lodash and it works fine. Can you run the tests and let me know?

like image 190
Priyesh Diukar Avatar answered Oct 21 '22 09:10

Priyesh Diukar