QA Interview Hub · Knowledge base · Quizzes · Українська

TypeScript › Modules and tsconfig

ES Modules and CommonJS

ES Modules (import and export) are the language standard, while CommonJS (require and module.exports) is Node's historical module system. Node decides which one a file uses by the .mjs or .cjs extension, then by the "type" field in package.json, and without it by the syntax, so set the field explicitly. ESM has no require or __dirname: use import and import.meta.dirname instead.

TypeScript · Modules and config

Nobody touched the test and it failed: «require is not defined in ES module scope». What changed in the project?

A utility that read users.json through __dirname worked for a month. Then "type": "module" appeared in package.json (someone updated a dependency that needs ESM) and the same lines failed with «require is not defined in ES module scope». In the opposite direction the error is different: «Cannot use import statement outside a module». TypeScript itself has almost nothing to do with it: tests are written with import/export and the error arises on the border between the code and how Node decides which kind of module a file is.

How it works and why. Two module systems coexist in Node. CommonJS (require() and module.exports) was historically the only one. ES Modules (import and export) is the language standard: dependencies are declared statically, loading is asynchronous, top-level await is available. Node decides which system a particular file uses in this order:

How Node decides which module system a file uses

1. .mjs / .cjsalways ESM / always CommonJS2. "type" in package.json"module" or "commonjs" for .js3. No fieldNode looks at the syntax of the file
Figure 1. An explicit type field in package.json removes guesswork: it is worth setting always.

The third step is newer. Without the "type" field Node first treats a .js file as CommonJS, and since versions 22.7 and 20.19 runs it as ESM if it sees ESM syntax (import/export, import.meta, top-level await). It is convenient but unpredictable: the same file behaves differently depending on its content and Node postpones the decision until parsing. So an explicit "type" field remains the right choice.

Example: migrating a utility to ESM. The initial CommonJS code:

// before: CommonJS
const path = require('node:path');
const users = require(path.join(__dirname, 'users.json'));
{
  "name": "e2e",
  "type": "module"
}

After adding "type": "module" this file fails: in ESM there is no require, no __dirname and no module.exports. The fix:

// after: ESM ("type": "module")
import path from 'node:path';
import { readFile } from 'node:fs/promises';

const file = path.join(import.meta.dirname, 'users.json');
const users = JSON.parse(await readFile(file, 'utf8'));

import.meta.dirname replaces __dirname (available since Node 20.11), and JSON is read through fs or import ... with { type: 'json' }. Note also the top-level await: it does not exist in CommonJS and simply works in ESM.

What this means for TypeScript code. In TS tests the import/export syntax is almost always written and the runner or compiler converts it to the needed format. Playwright transpiles TS files itself, so there is no separate build step, and the choice of ESM or CommonJS depends on the "type" field in package.json. Playwright does not check types: a test with a type error will run. So CI needs a separate npx tsc --noEmit step. Useful import forms:

import type { Page, Locator } from '@playwright/test'; // type only, erased
import { test, expect } from '@playwright/test';

export { LoginPage } from './login-page.js';           // re-export, a barrel file
export type { Account } from './models.js';

import type guarantees that the import will vanish completely after compilation. It matters with the verbatimModuleSyntax option, which requires type imports to be marked explicitly, and helps not to create runtime circular dependencies. A named export is better than default: the name is fixed and auto-import and refactoring work better. The .js extension in paths to your own files is required by the compiler under module: NodeNext in an ESM project (see the next lesson); Playwright itself resolves both a path with .js and one without an extension.

Limits and alternatives: CommonJS meets ESM. ESM can import CommonJS without problems. The reverse used to be forbidden; now in current Node versions (22.12 and 20.19 and later) require() can load an ES module if its graph has no top-level await. If it does, you get ERR_REQUIRE_ASYNC_MODULE and what remains is the dynamic import(), which works from both worlds and returns a promise. Also Node 24 runs .ts files directly, stripping the types, without a transpiler. It has its own rules: import type is mandatory for types, paths need the .ts extension and enum and parameter properties are not supported.

Common mistakes.

  • Adding "type": "module" and leaving require/__dirname in helper scripts: «require is not defined in ES module scope».
  • A file with import in a package with "type": "commonjs": «Cannot use import statement outside a module».
  • Relying on syntax detection instead of an explicit "type": behaviour depends on the Node version.
  • Assuming Playwright checks types: type errors do not stop the run, only tsc --noEmit catches them.
  • Importing a type with a plain import: an error under verbatimModuleSyntax and a runtime failure in Node type-stripping mode.

Check yourself

In a package without the "type" field the file helpers.js contains import fs from 'node:fs' and runs in Node 24. Why does it work and why should you not rely on it?

Answer

Node first tries the file as CommonJS, sees ESM syntax and reruns it as ESM (syntax detection, in 22.7 and 20.19 and later). It works only on modern Node, costs extra parsing and may differ between environments. An explicit "type": "module" makes the behaviour the same.

A CommonJS file calls require('./config.mjs') and Node throws ERR_REQUIRE_ASYNC_MODULE. What is in config.mjs and how to get around it?

Answer

The graph of config.mjs has a top-level await and require() is synchronous and cannot load such a module. Ways around: a dynamic await import('./config.mjs') inside an async function, or moving the top-level await into a function.

In an interview. Junior: Node has CommonJS with require and ES Modules with import. For .js the choice is set by the "type" field in package.json. Playwright transpiles TS itself but does not check types, so CI needs tsc --noEmit. Middle/Senior: The order is: the .mjs/.cjs extension, then "type", and without the field Node looks at the syntax. So I set "type" explicitly. ESM has no require or __dirname, instead there are import.meta.dirname, import (or createRequire when you need require itself); require() of ESM works in current Node but not with top-level await.

More articles in this chapter