ES modules
- Node.js course
- Beginner
- Lesson 3/116
- 5 min
Learn ES module syntax with import and export.
What are ES modules?
ES modules are JavaScript's modern module system. They let you reuse code from one file in another. This is the recommended approach in Node.js 22.
To export something from a module, you use the export keyword; to import from another module, you use import. ESM is enabled with the .mjs extension or by setting "type": "module" in package.json.
This course uses ESM throughout.
import and export
To export a function, you write export at the start of its definition. For example, export function greet(name) { ... }.
To use this function in another file, you write import { greet } from './greet.js'. The curly braces specify the exported name; from links the file path.
This way, code is split into small pieces and becomes easier to maintain.
Practice Export a function
Define a greet(name) function with export. The function should return the concatenation of 'Hello, ' and name. Then call console.log with greet('Alex').
Starter code
// Define greet with export
// Then call greet('Alex') and log itSample solution
export function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alex"));Expected output
Hello, Alex
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the module concepts
| Term | Meaning |
|---|---|
import |
Bring in |
export |
Send out |
.mjs |
ESM file extension |
"type": "module" |
Enable ESM |
2 import syntax
____ { greet } from "./greet.js";
import { greet } from "./greet.js";
Explanation: import is the ESM keyword for bringing in.
3 What does export do?
- Deletes a value
- Makes a value available in other files Correct answer
- Renames a value
- Hides a value
Explanation: export sends a value out.