javascript - How does ESM tree-shakingdead code elimination work? - Stack Overflow

I'm curious how tree-shakingdead code elimination of ESM works. I'm using Typescript for var

I'm curious how tree-shaking/dead code elimination of ESM works. I'm using Typescript for various Node.js projects and I started to export my own ESM packages (tsc --module es2015 --target es5 --outDir dist/esm) instead of CJS packages. Moreover, I tried to replace dependencies (like lodash) that are only available as CJS module with libraries that are available as ESM.

When I build a project, my entire TS codebase (./src) is transpiled to JS (./dist); dependencies are still taken from (./node_modules). No tree-shaking performed.

I guess I'd still need a bundler (like Webpack) that needs (at least) an entry point so that it can shake away everything that's not needed, so that I can reduce the package size of (e.g.) an AWS lambda? Is this something you would do?

I'm curious how tree-shaking/dead code elimination of ESM works. I'm using Typescript for various Node.js projects and I started to export my own ESM packages (tsc --module es2015 --target es5 --outDir dist/esm) instead of CJS packages. Moreover, I tried to replace dependencies (like lodash) that are only available as CJS module with libraries that are available as ESM.

When I build a project, my entire TS codebase (./src) is transpiled to JS (./dist); dependencies are still taken from (./node_modules). No tree-shaking performed.

I guess I'd still need a bundler (like Webpack) that needs (at least) an entry point so that it can shake away everything that's not needed, so that I can reduce the package size of (e.g.) an AWS lambda? Is this something you would do?

Share Improve this question asked Aug 21, 2020 at 9:29 DanielDaniel 9041 gold badge13 silver badges34 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6 +50

When you use import instead of require, the transpiler is able to build the dependency tree on pile time (that is why you cannot dynamically import code).

For example, if you write this:

import { myfunc } from 'mylib';

The transpiler understands that you only need the myfunc function from mylib. If mylib includes other functions that are not used by myfunc, the transpiler can remove them from the bundle.

This is the short version. Tree-shaking is actually more plex than that. Webpack has a good article about it if you want to learn more:

https://webpack.js/guides/tree-shaking/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745183351a4615521.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信