ES Modules in Node
An ES module uses import and export. ES is short for ECMAScript, the standard name for JavaScript.
The module file
This file is greet.mjs. It shares its function with export.
export function greet(name) {
return "Hello, " + name + "!";
}Load the module
This line takes greet from greet.mjs.
import { greet } from "./greet.mjs";Call the shared function
This line calls the shared function.
console.log(greet("Maya"));Example
import { greet } from "./greet.mjs";
console.log(greet("Maya"));
console.log(greet("Sam"));Key points
- import loads a module in ES module style.
- export shares a function from a module.
- A file with a .mjs ending uses ES modules.
- The import path needs ./ and the .mjs ending.
- Write import { greet } to take only the greet function.
- The braces in import name the function to take.
In this example, the first line takes greet from greet.mjs with import. The file greet.mjs shares its greet function with export. The first print greets Maya. The second print greets Sam.
Note
A .mjs file cannot use require, so use import there.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which ending marks a file as an ES module?