- The Asynchronous Module Definition (AMD) format is used in browsers and uses a
define function to define modules.
- The CommonJS (CJS) format is used in Node.js and uses
require and
module.exports to define dependencies and modules. The npm ecosystem is built upon this format.
- The ES Module (ESM) format. As of ES6 (ES2015), JavaScript supports a native module format. It uses an
export keyword to export a module’s public API and an
import keyword to import it.
- The System.register format was designed to support ES6 modules within ES5.
- The Universal Module Definition (UMD) format can be used both in the browser and in Node.js. It’s useful when a module needs to be imported by a number of different module loaders.
A background on modules
JavaScript programs started off pretty small — most of its usage in the early days was to do isolated scripting tasks, providing a bit of interactivity to your web pages where needed, so large scripts were generally not needed. Fast forward a few years and we now have complete applications being run in browsers with a lot of JavaScript, as well as JavaScript being used in other contexts (Node.js, for example).
It has therefore made sense in recent years to start thinking about providing mechanisms for splitting JavaScript programs up into separate modules that can be imported when needed. Node.js has had this ability for a long time, and there are a number of JavaScript libraries and frameworks that enable module usage (for example, other CommonJS and AMD-based module systems like RequireJS, and more recently Webpack and Babel).
The good news is that modern browsers have started to support module functionality natively, and this is what this article is all about. This can only be a good thing — browsers can optimize loading of modules, making it more efficient than having to use a library and do all of that extra client-side processing and extra round trips.
Introducing an example
To demonstrate usage of modules, we’ve created a simple set of examples that you can find on GitHub. These examples demonstrate a simple set of modules that create a <canvas>
element on a webpage, and then draw (and report information about) different shapes on the canvas.
These are fairly trivial, but have been kept deliberately simple to demonstrate modules clearly.
Note: If you want to download the examples and run them locally, you’ll need to run them through a local web server.