Important Note: This response is based on the assumption that you are coding using ECMAScript Module Syntax, which has become the standard in the industry.
To bundle or not to bundle? It's crucial to understand that bundlers serve two main purposes:
- They consolidate multiple source files into one
- They have the ability to produce code in various module formats (ESM, CommonJS, UMD)
Advantages of Bundling
Providing a Unified File
Having a single file comes with its advantages. Some individuals still prefer simply dragging and dropping a single *.js file into their project. This is particularly helpful for newcomers who may not be familiar with using a bundler.
Moreover, a single file can be effortlessly imported from CDNs like unpkg and JSDelivr, enabling direct linking to files in NPM packages. Conversely, a library distributed as multiple files incurs multiple network requests, leading to longer initial load times.
Supporting Legacy Browsers and Runtimes
The decision to bundle or not is independent of transpilation and polyfilling. Therefore, the argument that "bundling is necessary to support old browsers" is generally invalid.
However, there are exceptions with old browsers that do not support ES Modules, requiring bundling. Additionally, some non-Node.js JavaScript runtimes (e.g., Mozilla Rhino) do not support ES Modules either.
Restricting the API Surface Area
theoretically it is easier for consumers to import just the parts they want
This approach can backfire if users try to delve into your package and import individual files:
import {someFunc} from 'amazing-lib/dist/some/file.js'
someFunc() // Accessing an internal feature!
By doing so, they can access the inner workings of your library in unexpected ways, potentially causing unforeseen side effects. Bundling eliminates this risk, allowing you to modify your library without worrying about breaking user applications.
Note that with the introduction of package entry points, concerns regarding accessing internal features have diminished. According to the documentation:
Packages implementing the "exports" field will restrict consumers from utilizing any undefined entry points
Disadvantages of Bundling
Increased Effort
Naturally, setting up and configuring a bundler requires time and effort. Despite advancements in tooling, this process can still be cumbersome and contribute to slower deployment times. Furthermore, your node_modules directory might grow larger.
Who Chooses Not to Bundle?
In the realm of modern web development, most serious developers opt to use a bundler for their projects. Particularly those targeting browsers lacking ESM support need bundlers, as many library authors no longer provide CJS or UMD bundles. While bundling may benefit certain users, it caters more to a diminishing subset of individuals.