桶形文件和摇树 [英] Barrel file and Tree Shaking

查看:78
本文介绍了桶形文件和摇树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个示例存储库,显示了此线程中报告的问题的示例:我试图了解将Barrel文件从库项目中导出函数和类的效果,将其导入到另一个使用webpack并应能够进行树状捆绑的项目中时的作用.

I'm trying to understand what's the effect of using a Barrel file to export functions and classes from a library project when importing it into another project that use webpack and should be able to treeshake the bundle.

想象我有一个项目:

图书馆

  • index.ts

  • index.ts

libA.ts

libB.ts

index.ts具有以下代码:

index.ts has this code:

export { LibAMain } from 'LibA';
export { LibBMain } from 'LibB';

因此,我使用索引作为桶文件导出我要在库中开发的所有功能.

So I'm using index as a barrel file to export all the functions I'm going to develop in my library.

第二个项目将是:

库用户

  • index.ts

Index.ts具有以下代码:

Index.ts has this code:

import { LibAMain } from 'library'

LibAMain();

现在:库用户是使用webpack构建的,我希望能够对MyLib中未使用的库进行树状交换,但是当我查看生成的包时,我看到它包含启动LibA.js和LibB.js,不应该在那里:

Now: library-user is builded using webpack, which I expect to be able to treeshake the unused libraries in MyLib, but when I look into the generated bundle I see that it contains boot LibA.js and LibB.js, which shouldn't be there:

如果我将index.ts更改为:

If I change index.ts to:

import { LibAMain } from 'library/lib/LibA'

LibAMain();

然后webpack很好地完成了工作,我在最终的捆绑包中只看到LibA:

then webpack does its job well and I only see LibA in the final bundle:

TL; DR:如何继续使用桶索引文件,仅从库"中导入所有内容,但仍然可以进行树状握手?

TL;DR: How can I keep using the barrel index file and just import everything from 'library' but still have the treeshaking working?

谢谢您的帮助:)

推荐答案

它看起来像是代码中的模块问题,而不是webpack.
tsconfig.json

It looks like a module problem in your code, not webpack.
tsconfig.json

...
"module": "commonjs",
...

Commonjs模块系统不支持 webpack中的树摇(仅直接导入,就像您在作品mylib/libA上所做的一样.)
要修复github存储库中的树状抖动,您应该在tsconfig.json中使用module:es2015esnext.

Commonjs modules system doesn't support tree shaking in webpack (only direct imports like you did it above works mylib/libA).
To fix tree shaking in your github repo you should use module: es2015 or esnext in tsconfig.json.

...
"module": "esnext",
...

但是您是对的-不幸的是,摇树并不是webpack的最佳选择.
有几种方法可以更好地摇树:

But you are right - unfortunetely treeshaking is not webpack's best side.
There are several approaches how to shake your tree better:

  1. 用于改善树木摇晃的插件
  2. 副作用 webpack选项
  3. 使用的导出 webpack选项
  4. webpack移到rollup.汇总默认情况下具有一流的树状摇动功能(对于大型项目,我不建议这样做).
  1. Plugin to improve treeshaking
  2. Side effects webpack option
  3. Used exports webpack option
  4. Move from webpack to rollup. Rollup has first-class tree shaking by default (I don't recommend to do it for large projects).

这篇关于桶形文件和摇树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆