How do you tell Node.js to treat your files as ES modules?
Set "type": "module" in package.json so .js files are ESM, or use the .mjs extension for individual files. Use .cjs to force CommonJS inside an ESM project.
Explain it simply
Node has to decide how to read each .js file, and it cannot guess from the content alone. It looks for two hints: the file extension and the nearest package.json.
.mjsis always an ES module..cjsis always CommonJS..jsfollows the"type"field of the closestpackage.json:"module"means ESM, anything else (including no field) means CommonJS.
Example
{
"name": "fest-registration",
"version": "1.0.0",
"type": "module",
"main": "src/index.js"
}With this file, import express from "express" works in src/index.js. Without "type": "module" you would see SyntaxError: Cannot use import statement outside a module.
Rules that change once you switch to ESM:
- Relative imports need the full extension:
./utils.js, not./utils. require,module.exports,__dirnameare not available.- You can use
awaitat the top level.
What to say in the interview
"I add type: module to package.json, or name files .mjs. The type field applies to every .js file below that package.json, and .cjs lets me keep a legacy file as CommonJS."
Common mistakes
- Forgetting the
.jsextension in relative imports. - Leaving old
requirecalls in a package that is now ESM.