Member-only story
What Are CJS, AMD, UMD, ESM, System, and IIFE?
Module formats illustrated with Rollup examples
Modern JavaScript projects need a bundler to compile small pieces of code into something larger and more complex, such as a library or application. The popular bundlers are webpack, Rollup, Parcel, RequireJS, and Browserify. They transform JavaScript code into modules that can be loaded as one bundle.
A bundle can be arranged in different formats. In this article, we are going to present real examples of the CJS, AMD, UMD, ESM, System, and IIFE formats.
Bundlers and Formats
This is a standard HTML file that includes a stylesheet on line 5 and a JavaScript file on line 6:
Putting all JavaScript code into one file works for a simple case. As projects scale up, we need to modularize code into independent modules with separate namespaces. In addition to better organization, modularization brings the capabilities of encapsulation, dependency management, and reusability.
This is how a bundler comes into the picture. It is needed to compile small pieces of JavaScript code, along with stylesheets and images, into something larger and more complex, such as a library or application.
How should a bundler format the bundled code as an output? There are a number of choices, and the following formats are defined by Rollup:
cjs
(CommonJS) — Suitable for Node and other bundlers (alias:commonjs
).amd
(Asynchronous Module Definition) — Used with module loaders like RequireJS.umd
(Universal Module Definition) — Works asamd
,cjs
, andiife
all in one.es
– Keep the bundle as an ES module file. Suitable for other bundlers and inclusion as a<script type=module>
tag in modern browsers (alias:esm
,module
).system
– Native format of the SystemJS loader (alias:systemjs
).iife
– A self-executing function…