Each JavaScript file keeps its values to itself. To use a value in another file, write export in front of it in its own file, then import it by name where you need it. A file that does this is called a module.
Every command and output on this page is real, run with Node.js 26.13.1 on macOS.
Syntax
export const name = value;
import { name } from './file.mjs';
export: shares the value that follows from this file, under its name.import { name }: brings in that value by the same name. List more names with commas:{ a, b }.'./file.mjs': where the value comes from../means the same folder as this file.
See export (opens in a new tab) and import (opens in a new tab) on MDN.
Prerequisites
- Node.js, to run the example. Install it from the Node.js download page (opens in a new tab).
The Example
A list of book titles in a file named books.mjs, used by a second file, main.mjs. The .mjs ending tells Node.js that these files use import and export.
Step 1: Export the Value
export const books = ['Salt and Starlight', 'A Map of Quiet Places'];
Step 2: Import It in Another File
Save this file in the same folder:
import { books } from './books.mjs';
console.log(books);
Step 3: Run It
node main.mjs
[ 'Salt and Starlight', 'A Map of Quiet Places' ]
main.mjs printed the list that lives in books.mjs.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Importing a name the file doesn’t export: import { titles } from './books.mjs' | Node.js stops before running anything, with SyntaxError: The requested module './books.mjs' does not provide an export named 'titles' | Use the exact name after export, here books |
The terminal shows that error like this:
import { titles } from './books.mjs';
^^^^^^
SyntaxError: The requested module './books.mjs' does not provide an export named 'titles'
FAQ
Can one file export more than one value?
Yes. Put export in front of each one, and import the ones you need: import { a, b } from './file.mjs'.
Why .mjs and not .js?
Node.js reads a .mjs file as a module, so import and export work in it. Many projects keep .js and set "type": "module" in package.json instead.
Conclusion
Write export in front of a value to share it, and import { name } from './file.mjs' to use it in another file. The names must match exactly.
Additional Resources
- export (opens in a new tab) (MDN)
- import (opens in a new tab) (MDN)
- JavaScript modules (opens in a new tab) (MDN)
- Modules: ECMAScript modules (opens in a new tab) (Node.js docs)
JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.
0 comments