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 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/

本文标签: javascriptHow does ESM treeshakingdead code elimination workStack Overflow