Modules

ECMAScript modules

CommonJS modules work quite well and, in combination with NPM, have allowed the JavaScript community to start sharing code on a large scale.

But they remain a bit of a duct-tape hack. The notation is slightly awkward—the things you add to exports are not available in the local scope, for example.

And because require is a normal function call taking any kind of argument, not just a string literal, it can be hard to determine the dependencies of a module without running its code.

This is why the JavaScript standard from 2015 introduces its own, different module system.

It is usually called ES modules, where ES stands for ECMAScript .

The main concepts of dependencies and interfaces remain the same, but the details differ.

For one thing, the notation is now integrated into the language.

Instead of calling a function to access a dependency, you use a special import keyword.

1 import ordinal from "ordinal";
2 import {days, months} from "date-names";
3
4 export function formatDate(date, format) { /* ... */ }

Summary

Modules provide structure to bigger programs by separating the code into pieces with clear interfaces and dependencies.

The interface is the part of the module that’s visible from other modules, and the dependencies are the other modules that it makes use of.

Because JavaScript historically did not provide a module system, the CommonJS system was built on top of it. Then at some point it did get a built-in system, which now coexists uneasily with the CommonJS system.

A package is a chunk of code that can be distributed on its own.

NPM is a repository of JavaScript packages.

You can download all kinds of useful (and useless) packages from it.