Node.js and CommonJS
The Big Idea
The modules you have been using work in the browser. Node.js — which runs JavaScript on the server — has its own module system called CommonJS, with slightly different rules. You will encounter this in Bootcamp. For now, just understand what it is and how it differs.
Your Roadmap
| Section | Time | Required? |
|---|---|---|
| CommonJS vs ESM | 15 min | ⚑ Required |
| File extensions in Node.js | 15 min | ⚑ Required |
CommonJS vs ESM
The browser uses ESM (ECMAScript Modules) — the import/export syntax you have been using.
Node.js was built on CommonJS, which uses require() and module.exports instead.
| ESM (browser) | CommonJS (Node.js) | |
|---|---|---|
| Import | import { fn } from './file.js' | const { fn } = require('./file') |
| Export | export function fn() {} | module.exports = { fn } |
These are the same idea — sharing code between files — with different syntax.
You will not need to write CommonJS in Foundations. This section is awareness for when you see it in Bootcamp.
File extensions in Node.js
By default, Node.js treats .js files as CommonJS. That means import and export will not work in a .js file by default.
To use ESM in Node.js, use .mjs as your file extension:
// hype-the-crowd.mjsexport default function hypeTheCrowd(call, response) {console.log(`When I say ${call}, you say ${response}!`)console.log(`ME: ${call.toUpperCase()}!`)console.log(`CROWD: ${response.toUpperCase()}!`)console.log(`ME: I can't hear you!`)}
// main.mjsimport hypeTheCrowd from './hype-the-crowd.mjs'hypeTheCrowd('cheese', 'cake')
Run it in your terminal:
node ./main.mjs
The browser does not care about file extensions — it only checks for type="module" on the script tag. Node.js uses the extension to decide which module system to use.
How to know you've nailed it
| Level | You can... | ||
|---|---|---|---|
| 🪨 | Intro Climb | Explain the difference between ESM and CommonJS in plain language | ⚑ Required |
| 🧗 | Core Ascent | Describe when you would use .mjs vs .js in a Node.js project | ⚑ Required |
| 🏔️ | Summit | Run the .mjs example in your terminal and confirm it works | ◎ Optional |