如何准备lib以使其与摇树兼容?

问题描述 投票:0回答:1

我有一个使用Typescript创建的插件,我需要在this plugin中激活“摇树”。没有webpack,有什么方法可以启用此功能吗?

typescript webpack plugins tree-shaking
1个回答
1
投票

摇树是捆绑程序为了删除lib的未使用代码而应用的过程。

这意味着作为一个lib,您需要导出可摇树的版本(esm),因为您不知道消费者不会使用什么代码。

如果您的代码将同时在环境,节点和浏览器中使用,则您需要导出节点的cjs(commonJS)版本和浏览器使用的esm(ES模块)版本。

使用打字稿,您可以通过使用2个单独的配置一次运行tsc两次来实现这一点:

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

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

}

然后指定每次运行的配置。

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

package.json中添加2个条目。

{
  ...
  module: "dist/esm/index.js",
  main: "dist/cjs.index.js"
  ...
}
© www.soinside.com 2019 - 2024. All rights reserved.