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 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