Interview Q&A / Node.js

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do you tell Node.js to treat your files as ES modules?

SHORT ANSWER

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.

  • .mjs is always an ES module.
  • .cjs is always CommonJS.
  • .js follows the "type" field of the closest package.json: "module" means ESM, anything else (including no field) means CommonJS.

Example

json
{
  "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, __dirname are not available.
  • You can use await at 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 .js extension in relative imports.
  • Leaving old require calls in a package that is now ESM.

#nodejs#esm#package-json

Related questions

Practise more Node.js questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Node.js quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.