What are JavaScript Modules?

31 March 2022

A JavaScript module is just a JavaScript file. Modules allow a developer to break their script up into multiple files and exchange functionality between them.

JavaScript didn’t have this functionality natively for some time because, in the beginning, scripts added to websites were small and manageable. This changed with the rise in popularity of larger modern web applications and server-side applications using technologies like React and Node.js. The need for better code organization and easy use of third party libraries prompted the development of tools to support the concept of modules:

Since then, ECMAScript Modules were introduced in 2015 as the language standard and have been adopted by most major browsers.

Modules utilize import and export statements to share functionality between files. There are two types of exports, named and default.

Named

// named inline
export const animal = 'dog';

// named all-at-once
const age = 5;
const color = 'auburn';

export {
  age,
  color
};

Default

function eat() {
  const animal = 'dog';
  const name = 'Smalls';
  return name + ' ate their ' + animal + ' food.';
};

export default greeting;

The import statement handles these types of export statements slightly differently:

import { animal, age, color } from './inline.js';
import greeting from './default';

Further reading