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

SectionTimeRequired?
CommonJS vs ESM15 min⚑ Required
File extensions in Node.js15 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)
Importimport { fn } from './file.js'const { fn } = require('./file')
Exportexport 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.mjs
export 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.mjs
import 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

LevelYou can...
🪨Intro ClimbExplain the difference between ESM and CommonJS in plain language⚑ Required
🧗Core AscentDescribe when you would use .mjs vs .js in a Node.js project⚑ Required
🏔️SummitRun the .mjs example in your terminal and confirm it works◎ Optional