简体   繁体   English

如何准备 lib 与 tree-shaking 兼容?

[英]How prepare lib to be tree-shaking compatible?

I have a plugin created with Typescript and I need activate Tree-shaking in this plugin .我有一个用 Typescript 创建的插件,我需要在这个插件中激活 Tree-shaking。 Is there any way to enable this feature without webpack?有没有办法在没有 webpack 的情况下启用此功能?

Tree shaking is a process that bundlers apply in order to remove lib's unused code. Tree Shaking 是捆绑程序为了删除 lib 未使用的代码而应用的过程。

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.这意味着作为一个库,您需要导出一个可摇树的版本(esm),因为您不知道您的消费者不会使用哪些代码。

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.如果您的代码将同时用于环境、节点和浏览器,您需要为节点和esm (ES 模块)版本导出cjs (commonJS)版本以供浏览器使用。

With typescript you can achieve that by running tsc twice with 2 separate configs:使用 typescript 您可以通过使用 2 个单独的配置运行tsc两次来实现:

// 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.在您的package.json添加 2 个条目。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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