The previous lesson used require() and module.exports — CommonJS. Node also supports ES Modules, the import/export syntax you may already recognize from writing browser JavaScript. They do the same job with different syntax, and Node needs to be told which one a project is using.
By default, Node treats every .js file as CommonJS. To use import/export instead, add this to package.json:
{
"type": "module"
}(package.json is covered properly in the next lesson — for now, it's enough to know this one field switches the whole project's module style.)
// math.js
export function add(a, b) {
return a + b
}
export function multiply(a, b) {
return a * b
}// app.js
import { add, multiply } from './math.js'
console.log(add(2, 3))One real difference from CommonJS: ES Module imports need the full filename, including .js. Leaving it off, out of CommonJS habit, is the single most common mistake when switching.
Just like in browser JavaScript, a file can have one default export alongside any number of named ones:
// greet.js
export default function greet(name) {
return `Hello, ${name}!`
}
// app.js — no curly braces for a default import
import greet from './greet.js'
console.log(greet('Priya'))| CommonJS | ES Modules | |
|---|---|---|
| Syntax | require() / module.exports | import / export |
| File extension needed? | No | Yes, always |
| Where it's common | Older Node projects, some npm packages | New projects, matches browser JS syntax |
Which this course uses
For a brand-new project, ES Modules is the more consistent choice — it's the same syntax you already use in the browser. You'll still run into CommonJS constantly, though, since a huge number of existing npm packages are written with it. The rest of this course uses CommonJS, since it works with zero configuration and is what you'll see most often in tutorials and existing code.