What is the right way for better TreeShaking in webpack?

Viewed 1449

I was wondering, which one of the following two options is the right way for better Tree Shaking in webpack:

import { someFeature } from 'someModule'  // Option 1
import { isEmpty } from 'lodash' // Example 1

Or,

import someFeature from 'someModule/someFeature' // Option 2
import isEmpty from 'lodash/isEmpty' // Example 2
2 Answers

If I understand your question, I think you are asking for the benefits of named exports over default exports for better tree shaking or reducing the bundle size.

For better tree shaking, it is advised to use named export over default exports. According to this article,

Sometimes you can be tempted to export one huge object with many properties as default export. This is an anti-pattern and prohibits proper tree shaking:

So instead of using default export as example 1 use named export as example 2.

Example 1

// This is default export. Do not use it for better tree shaking
// export.js
 export default {
   propertyA: "A",
   propertyB: "B",
 }
// import.js
import export from './exports';

Example 2

// This is name export. Use it for better tree shaking
// export.js
 export const propertyA = "A";
 export const propertyB = "B";
// import.js
import { propertyA } from './exports';

So in the first example it will export both propertyA and propertyB while in the second it will only export propertyA which will reduce the bundle size.

No matter if you use option one or two, it will not be possible to "tree shake" unused things from your "someFeature" if that is one huge object or class with many properties and you are using only some of those properties. So the best option would be to chunk your "someFeature" into smaller pieces and export those smaller pieces as named exports.

Related