Skip to content

Using ESM Modules

While Node.js has supported modules since its inception, JavaScript itself lacked built-in module functionality for a long time, relying instead on systems like CommonJS and AMD. With the introduction of the ES6 standard, JavaScript finally supports native modules, known as ECMAScript Modules (ESM), which can be used in both browsers and Node.js.

Exporting with ESM

When not using ESM, we export JavaScript objects for external use with module.exports. For example, a module exporting two functions looks like this:

javascript
'use strict';
let s = 'Hello';

function out(prompt, name) {
    console.log(`${prompt}, ${name}!`);
}

function greet(name) {
    out(s, name);
}

function hi(name) {
    out('Hi', name);
}

module.exports = {
    greet: greet,
    hi: hi
};

To convert this to an ESM module, we use the export keyword for the functions we want to export:

javascript
let s = 'Hello';

function out(prompt, name) {
    console.log(`${prompt}, ${name}!`);
}

export function greet(name) {
    out(s, name);
}

export function hi(name) {
    out('Hi', name);
}

Save this as hello.mjs (note the .mjs extension).

Importing ESM Modules

You can create a main.mjs file to call the hello module:

javascript
import { greet, hi } from './hello.mjs';

let name = 'Bob';
greet(name);
hi(name);

In ESM, we use the export keyword to export functions and the import keyword to import them.

To export a single function like this:

javascript
module.exports = greet;

You can use export default:

javascript
export default function greet(name) {
    ...
}

Then import it like this:

javascript
import greet from './hello.mjs';

Note that ESM modules do not require 'use strict' at the top, as they default to strict mode.

Loading ESM in Browsers

In browsers, ESM modules can be loaded with type="module":

html
<html>
<head>
    <script type="module" src="./example.js"></script>
    <script type="module">
        greet('Bob');
    </script>
</head>
</html>

Or you can import directly in a script:

html
<html>
<head>
    <script type="module">
        import { greet } from './example.js';
        greet('Bob');
    </script>
</head>
</html>

Summary

When using JavaScript's built-in native modules, use the export and import keywords for exporting and importing. ESM modules automatically enable strict mode, so there's no need to declare 'use strict'.

Exercise

Try using ESM modules in the Node environment by downloading the exercise.

Using ESM Modules has loaded