DEV Community

Discussion on: How to write a tree-shakable component library

Collapse
 
dance2die profile image
Sung M. Kim

Thanks for the post, Lukas.

If I am not mistaken, this is because the ESM syntax allows bundlers to statically check which parts of your code are used and which are not, which is harder with require because it can be used in more dynamic ways,...

Wouldn't ESM have the same problem because of dynamic import()?

I am not sure if tree-shaking doesn't work if dynamic import is used.

Collapse
 
lukasbombach profile image
Lukas Bombach

My original source for this is this

exploringjs.com/es6/ch_modules.htm...

which is linked here

webpack.js.org/guides/tree-shaking/

If I try to understand it, I would guess that there is a difference when you do a static import like this

import x from "y";

and when you do a dynamic import like this

import(something)

This might seem like nothing, but I guess that when you do static code analysis and all you have is a string, you can see 100% by the syntax if it is a static import or a dynamic one. And the static one can be tree-shaken and I guess the dynamic one can't.

That's my guess at least.

Collapse
 
dance2die profile image
Sung M. Kim

You are right.

I dug around a bit, and the Webpack author commented that with dynamic import, tree shaking is now performed.

github.com/webpack/webpack.js.org/...