Q1. What are ES Modules in Node.js?
ES Modules (ESM) is the official ECMAScript module system, using import and export syntax. Node.js supports ESM alongside CommonJS. To use ESM, use .mjs extension or set "type": "module" in package.json. Example:
import express from 'express'; export const value = 42;Q2. How do ES Modules differ from CommonJS?
ESM uses import/export, is static (imports are hoisted), supports top-level await, and is asynchronous. CommonJS uses require/module.exports, is dynamic (can be conditional), and is synchronous. ESM also has stricter syntax - imports must be at top level and paths must be fully specified.
Q3. How do you use both CommonJS and ES Modules together?
ES Modules can import CommonJS modules using default import:
import pkg from 'cjs-module';. CommonJS cannot require ES Modules directly (use dynamic import() instead). The interoperability is handled by Node.js, but there are limitations. It's best to stick to one system per project.Q4. What are named exports and default exports in ESM?
Named exports:
export const name = 'value'; export function fn() {}. Import with import { name, fn } from './module'. Default export: export default function() {}. Import with import anyName from './module'. A module can have multiple named exports but only one default export.Q5. How do you enable ES Modules in a Node.js project?
Two ways: 1) Use .mjs file extension. 2) Add "type": "module" in package.json (then .js files are treated as ESM). Files with .cjs are always CommonJS. Once enabled, you must use import/export syntax and cannot use require without workarounds.
