Web Analytics

JavaScript Modules

Modern ~15 min read

What are Modules?

Modules allow you to break up your code into separate files. This makes it easier to maintain the code-base.

ES6 introduced a native way to use modules using import and export statements.

Note: Modules only work with the HTTP(s) protocol. A file-system protocol (file://) will not work.

Named Exports

You can create named exports two ways. In-line individually, or all at once at the bottom.

// person.js
export const name = "Jesse";
export const age = 40;

// OR
const name = "Jesse";
const age = 40;
export { name, age };

Default Exports

You can only have one default export in a file.

// message.js
const message = () => {
  const name = "Jesse";
  const age = 40;
  return name + ' is ' + age + 'years old.';
};

export default message;

Importing

You can import modules into a file in two ways, based on if they are named exports or default exports.

// Importing named exports
import { name, age } from "./person.js";

// Importing default export
import message from "./message.js";

Module Demo

Since modules require separate files, this demo simulates module behavior using an object pattern (Revealing Module Pattern), which was common before ES6 modules.

HTML
CSS
JS

Summary

  • Modules help organize code into separate files.
  • Use export to expose variables and functions.
  • Use import to bring them into other files.
  • Use type="module" in your script tag to enable module features.

Quick Quiz

How many default exports can a module have?

A
Zero
B
One
C
Two
D
Unlimited