JavaScript Modules

Back to JS page

Table of Contents

What are Modules?

JavaScript modules allow you to break up your code into separate files.

This makes it easier to maintain the code-base.

Modules are imported from external files with the import statement.

Modules also rely on type="module" in the <script> tag.

Module Files

A module file exports functions or objects using the export keyword. The main file imports them using import:

math.js - Module file:

export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
export const subtract = (a, b) => a - b;
export const divide = (a, b) => a / b;

Main HTML file:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Modules</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Module Files</h4>
<p id="demo"></p>

<script type="module">
import { add, multiply } from './math.js';

document.getElementById("demo").innerHTML =
  "5 + 3 = " + add(5, 3) + "<br>" +
  "5 * 3 = " + multiply(5, 3);
</script>

</body>
</html>

Example 1

Result View Example

Export and Import

You can export individual functions and import them by name:

message.js - Module file:

export const greeting = "Hello";
export function welcome(name) {
  return greeting + ", " + name + "!";
}
export const farewell = (name) => "Goodbye, " + name + "!";

Main HTML file:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Modules</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Export and Import</h4>
<p id="demo"></p>

<script type="module">
import { greeting, welcome, farewell } from './message.js';

document.getElementById("demo").innerHTML =
  greeting + "<br>" +
  welcome("John") + "<br>" +
  farewell("Jane");
</script>

</body>
</html>

Example 2

Result View Example

Export Objects

You can export entire objects from a module:

person.js - Module file:

export const person = {
  firstName: "John",
  lastName: "Doe",
  age: 30,
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

export const cars = ["BMW", "Volvo", "Saab", "Ford"];

Main HTML file:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Modules</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Export Objects</h4>
<p id="demo"></p>

<script type="module">
import { person, cars } from './person.js';

document.getElementById("demo").innerHTML =
  "Person: " + person.fullName() + "<br>" +
  "Age: " + person.age + "<br><br>" +
  "Cars: " + cars.join(", ");
</script>

</body>
</html>

Example 3

Result View Example

Document

Document in project

You can Download PDF file.

Reference