Skip to content

Rollup ES Library Bundle

Chris edited this page Mar 31, 2021 · 1 revision

Rollup ES Library Bundle

By default Rollup will resolve relative import paths and create a single bundled JS files. Any absolute path or named imports are collected and placed a the top of the bundle.

For libraries using NPM and designed to be used with tools like Webpack, Rollup, or Parcel. This default format is ideal. The bundle tool can resolve and load the named imports left untouched by Rollup.

Example

Using this config:

// rollup.config.js
export default {
  input: 'src/main.mjs',
  output: {
    file: 'dist/bundle.es.js',
    format: 'es'
  }
};

Rollup transforms this file:

// src/main.mjs
// named import
import { ResizeObserver } from '@juggle/resize-observer';
// file import
import { removeLastWord } from './removeLastWord';

Into this bundle:

// dist/bundle.es.js
// named import is untouched
import { ResizeObserver } from '@juggle/resize-observer';
// file import is resolved and included in the bundle
function removeLastWord(text) {
  return text.trim().substring(0, text.lastIndexOf(' '));
}

As you can see, the file import './removeLastWord' is resolved and bundled into the final result. But the named import '@juggle/resize-observer' was left as an import statement.

By default Rollup does not perform any translations, the code remains untouched. Transforming the files with Bable, Elm, or Typescript requires the use of plugins.

Why this format?

  • ✅ Smallest bundle.
  • ⚠️ Dependencies not included without plugins.

This is the best format for a small reusable library. Because the named imports are left as named imports, the file avoids bundling large external libraries into the code. These libraries can be hosted on a CDN to improve network and loading speed or bundled into the larger application that uses the library.

The downside is that the application must provide these libraries, and the knowledge to provide them. It also requires the application to provide a compatible version of the external libraries.

Why bundle at all, why not import src/main.mjs?

Since external libraries are not included, why bother bundling at all? If an application is using a bundler like Webpack, loading from the main source file directly appears to have the same effect.

If your code needs a processing step, like Babel, Typescript or even Haxe, then applications will expect the library to have been processed before released. Most configurations of Webpack and other bundlers will not pre-process files from node_modules/.

⚠️ If we leave those named imports unresolved, this will not work with the browser's native module system. It will work with systems like Webpack.