ES Modules: Using import and export

A module is a JavaScript file that exports one or more values (it can be objects, functions or variables), using the export keyword.

For example, a file can export a variable:

const age = 18

export { age }

Or a function:

function calculate() {}

export { calculate }

test.js

You can then import this value in another file.

Suppose the file is named test.js and it’s found in the same folder as the one you want to import from, you’ll write

import { calculate } from './test.js'

And you can use that function as if it was written in the same file.

Notice I used ./ to say “current file’s folder”. If the file is in another folder, you’ll need a relative path, for example ../../test.js if it’s 2 subfolders deep.

Using server-side JavaScript, when we’ll get to that (Node / Deno / Bun), you’ll also see how to import from built-in modules and 3rd party modules.

Lessons in this unit:

0: Introduction
1: ▶︎ Using import and export
2: .mjs files
3: Default exports
4: Multiple exports
5: Renaming exports
6: Using the `script` tag