Skip to main content
0 reactions

How to Export and Import a Value in JavaScript

Card titled Export and Import in JavaScript, labelled JavaScript basics, with four ticked lines: export const books, import books from ./books.mjs, and a bad name gives a SyntaxError.
How to Export and Import a Value in JavaScript

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

SyntaxJavaScript
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

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

books.mjsJavaScript
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:

main.mjsJavaScript
import { books } from './books.mjs';

console.log(books);

Step 3: Run It

TerminalBash
node main.mjs
OutputPlain text
[ 'Salt and Starlight', 'A Map of Quiet Places' ]

main.mjs printed the list that lives in books.mjs.

Common Mistakes

MistakeWhat happensDo 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:

Output (the lines that matter)Plain text
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

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

0 comments