简体   繁体   中英

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?

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 -c ./tsconfig.browser.json
tsc -c ./tsconfig.node.json

In your package.json add 2 entries.

{
  ...
  module: "dist/esm/index.js",
  main: "dist/cjs/index.js"
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM