Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How prepare lib to be tree-shaking compatible?

I have a plugin created with Typescript and I need activate Tree-shaking in this plugin. Is there any way to enable this feature without webpack?

like image 209
João Eudes Lima Avatar asked Nov 15 '25 21:11

João Eudes Lima


1 Answers

Tree shaking is a process that bundlers apply in order to remove lib's unused code.

That means that as a lib you need to export a version (esm) that is tree-shakable, because you don't know what code your consumers will not use.

If your code gonna be used in both envs, node & browsers, you will need to export cjs (commonJS) version for node & esm (ES modules) version for browser use.

With typescript you can achieve that by running tsc twice with 2 separate configs:

// tsconfig.browser.json
{
  "compilerOptions": {
    "module": "esnext",
    "outDir": "./dist/esm/",
    ...
  }

}
// tsconfig.node.json
{
  "compilerOptions": {
    "module": "commonjs",
    "outDir": "./dist/cjs/",
    ...
  }

}

Then specify the config for each run.

tsc -p ./tsconfig.browser.json
tsc -p ./tsconfig.node.json

In your package.json add 2 entries.

{
  ...
  "module": "dist/esm/index.js",
  "main": "dist/cjs/index.js"
  ...
}
like image 79
felixmosh Avatar answered Nov 18 '25 11:11

felixmosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!