Skip to content

Modules

Almost every language has the concept of modules, which is a way to integrate functionality declared in one file into another. Typically, the developer creates a * code library * that is responsible for handling related tasks. This library can be referenced by applications or other modules. To make the objects available to the outside world, functions, classes or variables, all you have to do is export them and then import them into other files as needed. A script becomes a module if it uses the keywords import and/or export.

Export

One way to export is to export the objects one by one. What is not exported will not be available directly outside the module.

export const numbers = [1, 2, 3, 4];
const students = ['Alex', 'Carol', 'Alicia']; // ❌ Not accessible from the outside of the module

export function consoleLogger() {
  console.log(numbers, students);
}

export class Student {
   constructor() {
     // ...
   }
}

However, instead of adding the word export to each object that you want to export, you can use a declaration that is added at the end of the module:

export { numbers, consoleLogger, Student };

Import

Importing is very easy. It is enough to open the curly bracket after the keyword import and list the objects that we want to import from the indicated module location.

import { consoleLogger, Student } from 'student.module.js';

If we want to import all exported module objects, just replace their name with an asterisk * and add an alias:

import * as StudentUtils from 'student.module.js';

Such an import allows you to access objects using a dot:

StudentUtils.consoleLogger();

Aliases can also be given to individual objects that we import:

import consoleLogger as Logger from 'student.module.js';

Using modules in the web browser

Scripts which use modules must be loaded by setting the type ="module" attribute in the <script> tag. Example:

<script type="module" src="/scripts/app.js"></script>