admin管理员组文章数量:1415100
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 badges1 Answer
Reset to default 6 +50When 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/
本文标签: javascriptHow does ESM treeshakingdead code elimination workStack Overflow
版权声明:本文标题:javascript - How does ESM tree-shakingdead code elimination work? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745183351a2646568.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论