什么是扁平捆绑,为什么 Rollup 在这方面比 Webpack 更好?

What is flat bundling and why is Rollup better at this than Webpack?

我最近一直在研究 rollup and seeing how it differs from Webpack and other bundlers. One thing I came across was that it is better for libraries because of "flat bundling". This is based on a tweet and from a recent PR for React to utilize Rollup

In my experience, Rollup is better at building libraries due to better optimizations around flat bundling (e.g. hoisting). 1/2

Webpack 2 may be better for you if you're bundling apps with code-splitting etc though. 2/2

虽然我不完全确定我理解这意味着什么。扁平化捆绑指的是什么?我知道 Rollup 的文档提到 treeshaking to help reduce bundle size but Webpack also has a way of doing this。可能是我没有完全理解这个概念。

请注意,这不是关于 Rollup 与 Webpack 的比较问题。对于对此感兴趣的人,有一个 comparison chart for that by Webpack。这主要是在问什么是平面捆绑?可能 Rollup 在内部做了什么来实现这一目标?

编辑:Rollup 支持代码拆分 - read article

编辑:Webpack 现在在某些情况下支持范围提升 — read the blog post here

我们可能对这个东西都有不同的定义,但我认为扁平捆绑只是意味着 'taking your modules and turning them into a single bundle' — 即 'flat' 是多余的。 React 16 的最大区别在于默认情况下您将使用预制包,而不是您的应用程序负责捆绑 React 的源模块(尽管总是有一个 prebuilt UMD bundle of React available,使用 Browserify 构建)。

相反,两者之间的最大区别在于 在模块边界 发生的情况。 webpack 的工作方式是将每个模块包装在一个函数中,并创建一个实现加载器和模块缓存的包。在运行时,依次评估每个模块函数以填充模块缓存。这种架构有很多优势——它可以实现代码拆分和按需加载以及热模块替换 (HMR) 等高级功能。

Rollup 采用不同的方法 — 它将所有代码放在同一级别(根据需要重写标识符以避免变量名称之间的冲突等)。这通常被称为“范围提升”。因此,没有每个模块的开销,也没有每个包的开销。你的 bundle 肯定会更小,而且评估速度也会更快,因为间接性更少(更多相关信息 — The cost of small modules)。权衡是这种行为依赖于 ES2015 模块语义,这意味着 webpack 的一些高级功能更难实现(例如 Rollup 不支持代码拆分,至少现在不支持!)。

简而言之,webpack 通常 更适合应用程序,而 Rollup 通常 更适合库。

我整理了一份 small gist illustrating the differences. You can also get a feel for Rollup's output by tinkering with the Rollup REPL