ES6 Modules

A module groups related functionality and data together and keeps it in one place. That makes our code easier to reuse and easier to maintain. Modules were added in ES6 (ECMAScript 2015), and they are the standard module system for JavaScript.

Modules are Files

ES6 modules live in separate files. Each file is a module. A module can contain classes, functions, variables, and other code, and any of it can be exported so that other modules can import it.

Using Modules in the Browser

Say we have a file named script.js with one variable declaration in it:

// script.js
const pi = 3.14159;

Suppose this script is linked to an HTML file:

<script src="script.js"></script>

The variable pi is now available in the global scope. If you open the HTML file in a browser and then open the browser’s console, you can access the variable pi.

To avoid polluting the global scope, we can use modules to encapsulate our code. This is particularly useful when working with larger codebases. All you need to do is add the type="module" attribute to the <script> tag:

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

Now, the variable pi is no longer available in the global scope. If you try to access it in the browser’s console, you will get an error.

To make the variable pi available in other parts of your code, you need to export it from the module.

Using Modules in Node.js

Node.js uses the CommonJS module system by default, which is different from ES6 modules.

To use ES6 modules in Node.js, you need to add the property "type": "module" to your package.json file. This tells Node.js to treat all JavaScript files as ES6 modules:

{
  "name": "my-node-app",
  "version": "1.0.0",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  }
}

Modules Create Their Own Scope

A module has its own scope. Variables and functions defined in a module are not accessible outside the module unless you export them. That prevents naming conflicts, and it makes the code easier to reason about.

In the following sections, we will see how to export values from a module and import them into other modules.