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

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


Edit: Rollup supports code splitting - read article

Edit: Webpack now supports scope hoisting in some situations — read the blog post here

We probably all have different definitions for this stuff, but I think flat bundling simply means 'taking your modules and turning them into a single bundle' — i.e, the 'flat' is redundant. The big difference in React 16 is that you'll consume a premade bundle by default, rather than your app being responsible for bundling React's source modules (though there was always a prebuilt UMD bundle of React available, built with Browserify).

Rather, the big difference between the two is what happens at the module boundaries. The way webpack works is that it wraps each module in a function, and creates a bundle that implements a loader and a module cache. At runtime, each of those module functions is evaluated in turn to populate the module cache. This architecture has lots of advantages — it makes it possible to implement advanced features like code-splitting and on-demand loading, and hot module replacement (HMR).

Rollup takes a different approach — it puts all your code at the same level (rewriting identifiers as necessary to avoid conflicts between variable names etc). This is often referred to as 'scope hoisting'. Because of it, there's no per-module overhead, and no per-bundle overhead. Your bundle is guaranteed to be smaller, and will also evaluate faster because there's less indirection (more information on that — The cost of small modules). The trade-off is that this behaviour relies on ES2015 module semantics, and it means that some of webpack's advanced features are much harder to implement (e.g. Rollup doesn't support code-splitting, at least not yet!).

In short, webpack is generally a better fit for apps, and Rollup is generally a better fit for libraries.

I've put together a small gist illustrating the differences. You can also get a feel for Rollup's output by tinkering with the Rollup REPL.