What is Bundling?
The five common module formats include,
- Immediately-Invoked Function Expressions, also known as IIFEs .
- Asynchronous Module Definition, also known as AMD.
- CommonJS, which was popularized by Node.
- The Universal Module Definition, which blends AMD with CommonJS.
- And finally, the ES6 module format.
Why ES6 Modules?
ES6 modules are also a win because you can't declare them dynamically. Now that sounds like a drawback because it reduces power, but this reduced power was a deliberate design decision because it makes our code statically analyzable. That's a fancy way of saying that it means that our code can be read and analyzed in a predictable way because the behaviour of our imports can't be changed at runtime. When code can be analyzed this way, we get benefits that I alluded to earlier when discussing editors. We get improved autocompletion support since your editor can determine clearly what functions are currently in scope from each imported module. This power leads to other wins, such as the ability to quickly alert you to invalid imports, to functions that don't exist, and so on.
Effectively, choosing ES6 modules means that your code fails fast. You find out about your mistakes more quickly, and often in a clearer manner.
The first bundler to reach mass adoption was RequireJS. RequireJS popularized the AMD pattern, also known as Asynchronous Module Definition, that we saw on a previous slide. However, since we're moving on to ES6 modules today, RequireJS has largely fallen out of favour. So let's shift our focus to more modern bundlers that we should be considering today.
Webpack is the most full-featured and powerful of the bunch, so Webpack's what Ollie-UI uses.
What really makes Webpack special is its ability to intelligently bundle and generate your CSS, images, fonts, and even your HTML. This means you can do things like inline images via Base64 encoding when they're small enough to justify saving an HTTP request. And it means you can hot reload your CSS changes in memory, via the built-in Web server. Webpack offers strategic bundle splitting. This helps avoid your users downloading all of your JS upfront. Instead, you can generate separate bundles for different sections of your app, so they're downloaded on demand.
Webpack also includes a built-in Web server that supports hot module reloading. Which means depending on the library or framework you're using, you may be able to hit save and immediately see the changes without having to do a full refresh. This helps speed development because you don't lose client-side state. This is especially helpful on complicated user interfaces and multi-step forms because you don't have to refill the form every time to test your changes. The code is hot reloaded in place, and your existing input field values and so on are maintained.