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
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!