ES Modules: .mjs files

What we wrote in the first ES modules lesson is correct, but it needs to run in an environment where ES modules are enabled.

Most modern tools like Next.js, Astro, SvelteKit etc will sort this out for you.

But if you try creating a test.js file in a folder with an export and you try to run it with node test.js (Node.js, not yet covered but bear with me):

const age = 18

export { age }


You’ll get an error like this:

(node:12384) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
export default age

SyntaxError: Unexpected token 'export'

It doesn’t work!

What we need to do is listen to what that error message says.

You can rename both files from .js to .mjs, making sure you also update the import path from './test.js' to './test.mjs', and things will work.

Or you can add a package.json file in the folder with this content:

  "type": "module"

and that will work without changing the file extension.

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!