JavaScript Modules: ES Modules (import/export) vs CommonJS (require)

Real projects are never one file. Modules let you split code into small files that each do one job, such as a config file, an API client, page objects and test helpers, and then share functions between them. JavaScript has two module systems: the modern standard ES Modules (import / export) and Node.js’s original CommonJS (require / module.exports). Playwright, Vite and most new tools use ES Modules, but you will still meet CommonJS in older code and many npm packages. In this lesson you will write both, learn how Node.js decides which one a file uses, and fix the errors that come from mixing them.

Advertisement

📖 What You’ll Learn: what a module is, CommonJS with require and module.exports, ES Modules with import and export, named vs default exports, renaming and namespace imports, .mjs, .cjs and “type”: “module”, file extensions in import paths, import.meta.dirname, top-level await, dynamic import(), using CommonJS packages from ES Modules, and organising a test project into modules.


📦 What Is a Module?

Definition: a module is a JavaScript file with its own private scope. Variables and functions inside it are invisible to other files unless the module exports them, and another file must import (or require) them to use them.

  • Organisation: one file per job, such as config.js, apiClient.js and loginPage.js.
  • No global clutter: two files can both have a variable called count without clashing.
  • Reuse: write a helper once and import it in every test file.
  • Packages: everything you install with npm is a module you import.
CommonJS (CJS)ES Modules (ESM)
Exportmodule.exports = { ... }export function ... / export default ...
Importconst x = require("./x")import x from "./x.js"
StandardNode.js onlyOfficial JavaScript standard (browsers and Node.js)
LoadingSynchronous, at the line where require runsLinked before the code runs; supports top-level await
Used byOlder Node.js code, many npm packagesModern tools: Playwright, Vite, Vitest, browsers

🧱 CommonJS: require and module.exports

In CommonJS a file puts what it shares on module.exports, and another file gets it with require(). The .js extension can be left out of the path:

📄 math.js

function add(a, b) {
  return a + b;
}

function multiply(a, b) {
  return a * b;
}

const PI = 3.14159;

module.exports = { add, multiply, PI };

📄 app.js

const { add, multiply, PI } = require("./math");   // destructure what you need
const math = require("./math");                     // or take the whole object

console.log(add(2, 3));
console.log(multiply(4, 5));
console.log(math.PI);
console.log(typeof require, typeof module.exports);

⌨️ Terminal

node app.js

🖥️ Output

5
20
3.14159
function object

A module’s code runs once, the first time it is required. Later require calls return the same cached object, so a module is a natural place for shared state such as a config or a counter:

📄 counter.js

console.log("counter.js is loading");
let count = 0;
module.exports = {
  increment() { count++; },
  value() { return count; },
};

📄 app.js

const counterA = require("./counter");
const counterB = require("./counter");   // cached: the file does NOT run again

counterA.increment();
counterA.increment();
console.log(counterB.value());
console.log(counterA === counterB);

⌨️ Terminal

node app.js

🖥️ Output

counter.js is loading
2
true

⚠️ Watch out: exports.add = add works, but exports = { add } does not: reassigning exports breaks its link to module.exports. When you want to export an object, always write module.exports = { ... }.


✨ ES Modules: import and export

ES Modules use the export keyword in front of declarations and import { ... } from to bring them in. In Node.js, a file ending in .mjs is always an ES module:

📄 math.mjs

export function add(a, b) {
  return a + b;
}

export function multiply(a, b) {
  return a * b;
}

export const PI = 3.14159;

📄 app.mjs

import { add, multiply, PI } from "./math.mjs";

console.log(add(2, 3));
console.log(multiply(4, 5));
console.log(PI);

⌨️ Terminal

node app.mjs

🖥️ Output

5
20
3.14159

Named and default exports

A module can have many named exports and at most one default export. Named imports must use the exported name (inside braces); a default import can use any name (no braces):

📄 loginPage.mjs

export const BASE_URL = "https://staging.example.com";
export const users = ["admin", "tester"];

export default class LoginPage {
  constructor(email) {
    this.email = email;
  }
  describe() {
    return `LoginPage for ${this.email} at ${BASE_URL}/login`;
  }
}

📄 app.mjs

import LoginPage, { BASE_URL, users as testUsers } from "./loginPage.mjs";
import * as pageModule from "./loginPage.mjs";     // namespace import: everything as one object

const page = new LoginPage("asha@sqatools.in");
console.log(page.describe());
console.log(BASE_URL, testUsers.length);
console.log(Object.keys(pageModule));

⌨️ Terminal

node app.mjs

🖥️ Output

LoginPage for asha@sqatools.in at https://staging.example.com/login
https://staging.example.com 2
[ 'BASE_URL', 'default', 'users' ]
SyntaxMeaning
export const x = 1Named export
export { a, b as beta }Export existing names, optionally renamed
export default valueThe one default export
import { a } from "./m.js"Import a named export
import { a as alias } from "./m.js"Import and rename
import anyName from "./m.js"Import the default export
import * as m from "./m.js"Import everything as an object
export { a } from "./m.js"Re-export (used in index.js barrel files)

💡 Tip: Prefer named exports for helpers and utilities: the names are checked when the module is linked, editors can auto-import them, and renaming is explicit. Use a default export when a file has one obvious main thing, such as a page object class.


Advertisement

🔍 How Node.js Decides: .mjs, .cjs and “type”: “module”

Node.js looks at the file extension first, then at the nearest package.json:

FileTreated as
*.mjsAlways an ES module
*.cjsAlways CommonJS
*.js with "type": "module" in package.jsonES module
*.js with "type": "commonjs" or no "type"CommonJS

Most modern projects add "type": "module" once and then use plain .js files with import:

📄 package.json

{
  "name": "esm-demo",
  "type": "module"
}

📄 greet.js

export default function greet(name) {
  return `Hello, ${name}!`;
}

📄 app.js

import greet from "./greet.js";

console.log(greet("Asha"));

⌨️ Terminal

node app.js

🖥️ Output

Hello, Asha!

File extensions are required in ES module imports

CommonJS lets you write require("./math"). ES modules do not guess: the path must be the exact file name, extension included.

📄 math.mjs

export function add(a, b) {
  return a + b;
}

export function multiply(a, b) {
  return a * b;
}

export const PI = 3.14159;

📄 app.mjs

import { add } from "./math";   // missing ".mjs"
console.log(add(1, 2));

⌨️ Terminal

node app.mjs

🖥️ Output

node:internal/modules/esm/resolve:241
    throw new ERR_MODULE_NOT_FOUND(
          ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/you/js-course/math' imported from /home/you/js-course/app.mjs
 {
  code: 'ERR_MODULE_NOT_FOUND',
  url: 'file:///home/you/js-course/math'
}

Node.js v26.13.0

The error shows the exact path Node.js looked for (/math with no extension). Write "./math.mjs" (or "./math.js" in a "type": "module" project). Tools such as TypeScript, Vite and Playwright’s loader resolve extensions for you, which is why you sometimes see imports without them.


⚖️ Other Differences You Will Notice

__dirname and __filename

CommonJS gives every file __dirname and __filename. They do not exist in ES modules; use import.meta.dirname and import.meta.filename instead (Node.js 20.11 and later):

📄 where.mjs

console.log(import.meta.filename);
console.log(import.meta.dirname);
console.log(typeof __dirname);

⌨️ Terminal

node where.mjs

🖥️ Output (Windows)

C:\Users\you\js-course\where.mjs
C:\Users\you\js-course
undefined

Top-level await

ES modules can use await at the top level, outside any async function. This is handy for loading config or test data before the rest of the file runs. In CommonJS this is a syntax error.

📄 config.mjs

const settings = await Promise.resolve({ baseURL: "https://staging.example.com", retries: 2 });
console.log("loaded:", settings.baseURL, "retries:", settings.retries);

⌨️ Terminal

node config.mjs

🖥️ Output

loaded: https://staging.example.com retries: 2

Strict mode and this

ES modules always run in strict mode, and top-level this is undefined. In CommonJS, top-level this is module.exports:

📄 strict.mjs

console.log("ESM this:", this);
try {
  undeclared = 5;           // strict mode: assigning an undeclared variable throws
} catch (e) {
  console.log(`${e.name}: ${e.message}`);
}

⌨️ Terminal

node strict.mjs

🖥️ Output

ESM this: undefined
ReferenceError: undeclared is not defined

📄 loose.cjs

console.log("CJS this === module.exports:", this === module.exports);

⌨️ Terminal

node loose.cjs

🖥️ Output

CJS this === module.exports: true

Advertisement

⚡ Dynamic import()

import() looks like a function call and returns a promise of the module. Use it to load a module only when needed, to choose a module at runtime, or to load an ES module from CommonJS code:

📄 reporters/text.mjs

export default function text({ passed, failed }) {
  return `Passed: ${passed}, Failed: ${failed}`;
}

📄 reporters/json.mjs

export default function json(results) {
  return JSON.stringify(results);
}

📄 app.mjs

async function loadReporter(type) {
  const mod = await import(`./reporters/${type}.mjs`);   // chosen at runtime
  return mod.default;
}

const results = { passed: 18, failed: 2 };
for (const type of ["text", "json"]) {
  const report = await loadReporter(type);
  console.log(report(results));
}

⌨️ Terminal

node app.mjs

🖥️ Output

Passed: 18, Failed: 2
{"passed":18,"failed":2}

🔗 Mixing the Two Systems

You often need a CommonJS package inside an ES module project, or the other way round:

  • ESM importing CommonJS: works. module.exports becomes the default import, and Node.js usually detects named exports too.
  • CommonJS loading ESM: use await import("./x.mjs"). Recent Node.js versions (22.12+, 20.19+) also allow require() of an ES module, as long as it does not use top-level await.

📄 math.cjs

function add(a, b) {
  return a + b;
}

function multiply(a, b) {
  return a * b;
}

const PI = 3.14159;

module.exports = { add, multiply, PI };

📄 app.mjs

import math from "./math.cjs";              // module.exports -> default import
import { add } from "./math.cjs";           // named exports detected from module.exports = { ... }

console.log(math.multiply(3, 3), add(10, 5));

⌨️ Terminal

node app.mjs

🖥️ Output

9 15

📄 math.mjs

export function add(a, b) {
  return a + b;
}

export function multiply(a, b) {
  return a * b;
}

export const PI = 3.14159;

📄 app.cjs

const esm = require("./math.mjs");          // require() of an ES module (modern Node.js)
console.log(esm.add(2, 2), esm.PI);

import("./math.mjs").then((m) => console.log("dynamic import:", m.multiply(2, 6)));

⌨️ Terminal

node app.cjs

🖥️ Output

4 3.14159
dynamic import: 12

⚠️ Watch out: Using import in a file Node.js treats as CommonJS gives SyntaxError: Cannot use import statement outside a module. Fix it by renaming the file to .mjs or adding "type": "module" to package.json. The opposite case, ReferenceError: require is not defined in ES module scope, means you used require in an ES module: switch to import.


🧪 Tester Scenario: Organising a Test Project into Modules

A typical automation project keeps configuration, test data, an API client and page logic in separate modules, and re-exports the helpers through one index.js (a “barrel” file) so test files have a single import line:

📄 package.json

{ "type": "module" }

📄 support/config.js

export const config = {
  env: "staging",
  baseURL: "https://staging.example.com",
  retries: 2,
};

📄 support/users.js

export const users = [
  { email: "admin@sqatools.in", password: "Admin#123" },
  { email: "locked@sqatools.in", password: "Locked#123" },
];

📄 support/apiClient.js

export class ApiClient {
  constructor(baseURL) {
    this.baseURL = baseURL;
  }
  login({ email }) {
    // a real client would call fetch(`${this.baseURL}/api/login`, ...)
    const ok = !email.startsWith("locked");
    return { email, status: ok ? 200 : 423 };
  }
}

📄 support/format.js

export function formatResult({ email, status }) {
  return `${status === 200 ? "✓" : "✗"} ${email} -> ${status}`;
}

📄 support/index.js

export { config } from "./config.js";
export { users } from "./users.js";
export { ApiClient } from "./apiClient.js";
export { formatResult } from "./format.js";

📄 login.test.js

import { config, users, ApiClient, formatResult } from "./support/index.js";

const api = new ApiClient(config.baseURL);
const results = users.map((u) => api.login(u));

for (const r of results) console.log(formatResult(r));
console.log(`env=${config.env} retries=${config.retries}`);

⌨️ Terminal

node login.test.js

🖥️ Output

✓ admin@sqatools.in -> 200
✗ locked@sqatools.in -> 423
env=staging retries=2

Playwright test projects follow the same pattern: page objects in pages/, fixtures in fixtures/, data in test-data/, each exported from its own module and imported by the specs.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Create a CommonJS module strings.js exporting upper(s) and reverse(s), and use both from app.js.

Show answer

📄 strings.js

module.exports = {
  upper: (s) => s.toUpperCase(),
  reverse: (s) => [...s].reverse().join(""),
};

📄 app.js

const { upper, reverse } = require("./strings");
console.log(upper("playwright"), reverse("abc"));

🖥️ Output

PLAYWRIGHT cba

Q2. Rewrite the same module as an ES module (strings.mjs) with named exports, and import it in app.mjs.

Show answer

📄 strings.mjs

export const upper = (s) => s.toUpperCase();
export const reverse = (s) => [...s].reverse().join("");

📄 app.mjs

import { upper, reverse } from "./strings.mjs";
console.log(upper("playwright"), reverse("abc"));

🖥️ Output

PLAYWRIGHT cba

Q3. Create logger.mjs with a default export function log(msg) that prefixes [test], plus a named export LEVEL = "info". Import both in one line.

Show answer

📄 logger.mjs

export const LEVEL = "info";
export default function log(msg) {
  console.log(`[test] ${msg}`);
}

📄 app.mjs

import log, { LEVEL } from "./logger.mjs";
log(`level is ${LEVEL}`);

🖥️ Output

[test] level is info

Q4. Import everything from math.mjs as a namespace object and print the names it exports.

Show answer

📄 math.mjs

export function add(a, b) {
  return a + b;
}

export function multiply(a, b) {
  return a * b;
}

export const PI = 3.14159;

📄 app.mjs

import * as math from "./math.mjs";
console.log(Object.keys(math).sort());
console.log(math.add(1, 1));

🖥️ Output

[ 'PI', 'add', 'multiply' ]
2

Q5. Use dynamic import() to load staging.mjs or production.mjs depending on a variable env, and print the base URL.

Show answer

📄 staging.mjs

export default { baseURL: "https://staging.example.com" };

📄 production.mjs

export default { baseURL: "https://www.example.com" };

📄 app.mjs

const env = "staging";
const { default: settings } = await import(`./${env}.mjs`);
console.log(settings.baseURL);

🖥️ Output

https://staging.example.com

Q6. This project has "type": "module" in package.json, but app.js fails with ReferenceError: require is not defined in ES module scope. Fix it.

const { add } = require("./math.js");
console.log(add(2, 3));
Show answer

With "type": "module", every .js file is an ES module, so require does not exist. Use import (with the extension):

📄 package.json

{ "type": "module" }

📄 math.js

export function add(a, b) {
  return a + b;
}

export function multiply(a, b) {
  return a * b;
}

export const PI = 3.14159;

📄 app.js

import { add } from "./math.js";
console.log(add(2, 3));

🖥️ Output

5

🧠 MCQ Quiz: ES Modules vs CommonJS

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which syntax belongs to ES Modules?
  2. How many default exports can a module have?
  3. How does Node.js treat a file ending in .mjs?
  4. What makes plain .js files ES modules in a project?
  5. Why does import { add } from "./math" fail in an ES module?
  6. What replaces __dirname in an ES module?
  7. What does a second require("./config") of the same file do?
  8. Which feature works only in ES modules?
  9. What does import() return?
  10. What do you get from import pkg from "./old.cjs"?

💼 Interview Questions and Answers

Q1. What is the difference between CommonJS and ES Modules?

CommonJS is Node.js’s original system: require() loads a file synchronously when the line runs and returns its module.exports. ES Modules are the language standard: import/export declarations are static, so tools can analyse them (tree shaking, early errors for missing exports). They are loaded asynchronously, support top-level await, run in strict mode and work in browsers too. In Node.js, .mjs or "type": "module" selects ESM; .cjs or the default selects CommonJS.

Q2. Named export vs default export: which do you prefer?

Named exports for most code: the imported name must match, editors auto-import them reliably, and renaming is explicit (import { a as b }). A default export suits a module with one main thing, such as a page-object class or a config object. Many teams prefer named exports everywhere for consistency and easier refactoring.

Q3. You get “Cannot use import statement outside a module”. What do you check?

Node.js is treating the file as CommonJS. Either rename it to .mjs, add "type": "module" to the nearest package.json, or switch the file to require. In a test runner, also check its config (for example Jest needs a transform or ESM mode), because the runner, not Node.js, may be loading the file.

Q4. How are modules useful in a test automation framework?

They separate concerns: configuration per environment, test data, API clients, page objects, fixtures and utilities each live in their own module and are imported where needed. This avoids duplication, keeps test files short and readable, makes helpers easy to unit test, and lets you change one implementation (for example the login flow) in a single place.


Advertisement

❓ Frequently Asked Questions

🤔 Should I use ES Modules or CommonJS for a new project?

ES Modules. Add "type": "module" to package.json and use import/export. Playwright, Vite, Vitest and modern Node.js all support it, and it is the official standard.

🤔 Can I use import in the browser?

Yes. Load the entry file with <script type="module" src="app.js"></script>; imports must use relative or absolute URLs, such as "./utils.js".

🤔 What is a barrel file?

An index.js that re-exports from several modules (export { a } from "./a.js") so other files can import everything from one path. Keep barrels small; very large ones slow down loading.

🤔 Why does TypeScript let me omit the .js extension?

TypeScript and bundlers resolve module paths themselves. Plain Node.js running ES modules needs the real file name, which is why compiled output and native ESM projects include extensions.


🏁 Summary

  • A module is a file with private scope that shares values by exporting them.
  • CommonJS: module.exports and require(), synchronous and cached; ES Modules: export and import, the official standard.
  • .mjs is ESM, .cjs is CommonJS, and .js follows "type" in package.json.
  • In ES modules: write the file extension, use import.meta.dirname, and enjoy top-level await.
  • Use dynamic import() to load modules on demand, and organise test projects into config, data, client and page modules.

Next, continue with Lesson 53: npm and package.json.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in