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
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:
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 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.
Related lessons: “tsconfig for a test project”, “Global types, .d.ts and environment variables”, “Literal types, as const and satisfies”.
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.
tsconfig for a test project
tsconfig.json is read in full by tsc and the editor, while Playwright takes only a few options from it and does not check types. So a test with a type error still runs, and types in CI are checked by a separate npx tsc --noEmit step. Useful options are strict, noUncheckedIndexedAccess and verbatimModuleSyntax, and include must cover every test directory, otherwise types there go unchecked.
TypeScript · Modules and config
A test with a type error runs and passes. So what is tsconfig for in a Playwright project?
The repository has a thirty-line tsconfig.json, but a test with an obvious type error (amount: "100" instead of a number) runs calmly and Playwright says nothing. Meanwhile the IDE underlines the same line in red. So the config works, but not where people expect. This lesson looks at what Playwright takes from it, what only tsc and the editor use, and which set of options is reasonable for a test project in 2026.
How it works and why.tsconfig.json is read by different consumers and each takes its own. The tsc compiler and the editor (language service) use it fully: they check types by all options. Playwright transpiles TS without type checking and takes only a small part of the whole config: allowJs, baseUrl, paths, JSX settings, useDefineForClassFields, references and extends. It needs target only to determine useDefineForClassFields. The tsconfig is taken nearest to each file, so a separate tsconfig.json in the tests directory applies only to them.
Who reads what from tsconfig
Playwright
Only a small part
paths, baseUrl, allowJs, JSX, extends, references. It does not check types: strict does not affect the run.
tsc / IDE
All options
strict, module, include, types, noEmit and the rest. This is where type errors appear.
Figure 1. Two consumers, not a choice: both need the config, and CI must run tsc separately.
strict: a group of checks (strictNullChecks, noImplicitAny, useUnknownInCatchVariables and others). Since TypeScript 6.0 it is on by default, but it is better to set it explicitly: the intent is visible and the config reads the same in older versions.
noUncheckedIndexedAccess: arr[0] and an index signature entry have type T | undefined, so an «empty list» does not pass unnoticed.
module: NodeNext: module and import resolution rules follow Node (moduleResolution is taken from it). For code a bundler builds you choose module: ESNext with moduleResolution: Bundler.
verbatimModuleSyntax: every import stays as written, so types are imported with import type; this also makes the code compatible with transpilers that cannot see types.
noEmit: type checking only, no JS is produced, running stays with Playwright.
types: which global type packages to include. Since TypeScript 6.0 the default is empty, so process without "types": ["node"] gives TS2591.
paths: aliases instead of ../../../pages. Playwright supports them and baseUrl is not needed for this: since TypeScript 6.0 it is deprecated (TS5101), and paths are written relative to the config file.
skipLibCheck: do not check .d.ts files. It speeds things up but also hides errors in your own .d.ts files.
What breaks and how to read it. A typical situation: module: NodeNext and verbatimModuleSyntax were enabled but package.json has no "type": "module". The file is then treated as CommonJS and the compiler complains about every import; the second error appears only after switching to "type": "module" (messages shortened):
src/a.ts: TS1295: ECMAScript imports and exports cannot be
written in a CommonJS file under 'verbatimModuleSyntax'.
(after "type": "module")
src/a.ts: TS2835: Relative import paths need explicit file
extensions in ECMAScript imports when '--moduleResolution'
is 'node16' or 'nodenext'. Did you mean './pages/login.js'?
(messages shortened)
The first line reads: ESM syntax in a CommonJS file. It is cured by either "type": "module" or changing module. The second line: in an ESM package under NodeNext relative imports need an extension, and it is .js even though the file on disk is .ts, because the compiler looks at the path that will be in the output JS:
import { LoginPage } from'@pages/login.js'; // through pathsimport { helper } from'./helper.js'; // relative path: .js even though the file is .tsimporttype { Account } from'./models.js'; // a type: verbatimModuleSyntax requires type
Limits and alternatives.include matters only to tsc and the editor: a file missing from the list is not checked although Playwright will run it. That is how a «new» tests folder easily ends up without type checking. For different parts of a repository a base tsconfig.base.json is made along with separate configs that inherit it through extends:
Project references (composite and references) solve a different task, building dependent projects in the right order, and a test repository rarely needs them. When the code is run not by Playwright but by Node 24 itself in type-stripping mode (node test.ts), it ignores tsconfig: paths do not apply there, subpath imports (#...) in package.json are needed, and the erasableSyntaxOnly option in tsc forbids enum and parameter properties, which this mode does not support.
Common mistakes.
Assuming strict in tsconfig will stop a Playwright run: only tsc checks types, and it is missing in CI.
include without the new tests folder: files run but their types are not checked.
Forgetting "types": ["node"] with TypeScript 6.0: process and Buffer are not found (TS2591).
Copying baseUrl, moduleResolution: node10 or esModuleInterop: false from old examples: in 6.0 these are deprecated options (TS5101, TS5107).
Importing your own files without an extension in an ESM package under NodeNext: TS2835.
Check yourself
The project has no tsc step in CI and a test has await page.goto(123). Why can the run be green and what must be added?
Answer
Playwright does not check types: it transpiles the file and runs it. Only the IDE or tsc will see the type error. A separate npx tsc --noEmit step must be added (and noEmit in the config prevents creating extra files).
Which tsconfig fields does Playwright need to resolve the import @pages/login, and which do not affect the run: paths, strict, include?
Answer
Only paths is needed: Playwright reads it for aliases. strict and include concern only type checking in tsc and the editor and do not affect running tests.
Related lessons: “ES Modules and CommonJS”, “Global types, .d.ts and environment variables”, “Why TypeScript in a test framework”.
In an interview.Junior: In tsconfig I enable strict, noEmit and paths for short imports. Playwright does not check types, so I run tsc --noEmit separately in CI. Middle/Senior: I know who reads what: Playwright takes paths, extends and a few other options, while strict, include, types matter to tsc and the IDE. I add noUncheckedIndexedAccess, verbatimModuleSyntax, an explicit "types": ["node"] (empty by default since TypeScript 6.0) and make sure include covers all test folders.
Global types, .d.ts and environment variables
A .d.ts file contains only type declarations without code, and process.env has type string | undefined because a variable may really be missing. So variables are read through one module that validates them (with a function or a schema such as zod) and fails with a clear message. Extending ProcessEnv or using the ! operator only removes undefined for the compiler and checks nothing at runtime.
TypeScript · Modules and config
CI did not set BASE_URL and the test opened the page «undefined/login». Why did TypeScript stay silent?
The new BASE_URL variable was added locally in .env and forgotten in CI. The run did not fail at the start: the test opened the address undefined/login relative to the config baseURL and failed a minute later with an unclear timeout. The code had process.env.BASE_URL!, so the compiler was silent. The topic of this lesson is what exactly TypeScript knows about the environment (variables, global objects, libraries without types) and how to make a missing variable break the test at once with a clear message.
How it works and why..d.ts files contain only type declarations, without code: they describe what exists somewhere else. They come from @types/... packages (for example @types/node describes process), from the libraries themselves, or are written by hand for JS packages without types and to extend existing ones. Which global type packages are visible is set by the types option in tsconfig: since TypeScript 6.0 it is empty by default, so "types": ["node"] must be listed explicitly, otherwise process gives TS2591.
The type of process.env is a dictionary where every value is string | undefined. That is honest: the variable may really be missing. All the ways to «make the type more convenient» simply remove undefined without any guarantee:
const url = process.env.BASE_URL!; // "!" says: there is surely a value hereawait page.goto(url + '/login');
// if the variable is missing url is undefined and the page is "undefined/login"
// env.d.ts: extending the type
declare global {
namespace NodeJS {
interfaceProcessEnv {
BASE_URL: string;
}
}
}
export {};
// now process.env.BASE_URL is string while CI may not have the variable
Three ways to get an environment variable
Wrong
! or extending ProcessEnv
The type says string while at runtime it may be undefined. The error shows up late and far from the cause.
Right
A module with a check or a schema
Reading and checking in one place: the test fails at the start with the variable name and the rest of the code gets a ready string.
Figure 1. Extending a type only tells the compiler «the variable exists»; only code can check that.
Example: a module with a check. One module reads the variables, checks them and hands out a typed object. All tests import env from here and do not touch process.env directly:
Now without the variable the run fails at once: «Missing env variable BASE_URL». Even better is checking with a schema: zod converts types right away (z.coerce.number()) and derives the type from it.
Where the variables come from: dotenv in playwright.config.ts, and in modern Node also the built-in --env-file flag and the process.loadEnvFile() method. In CI they are set as secrets or pipeline variables and not through a file.
Your own .d.ts: when and why. Extending a global type, for example window.appReady, is declared in a module file through declare global (hence export {} at the end):
// types/global.d.ts: a module file, hence export {}
declare global {
interfaceWindow {
appReady?: boolean;
}
}
export {};
// in a testawait page.waitForFunction(() => window.appReady === true);
For a JS library without types a minimal module declaration is enough. Here, on the contrary, the file must not be a module, that is no import/export, otherwise it becomes an augmentation of an existing module:
// types/legacy-lib.d.ts: a file WITHOUT import/export, this declares a module
declare module 'legacy-lib' {
exportfunctionparse(input: string): number;
}
Limits and alternatives. With skipLibCheck: true the compiler checks no .d.ts files at all, including your own, so errors in them may go unnoticed. If one repository has both Cypress and Jest, their global describe, it and expect clash, and then separate tsconfigs are set up for different parts: a base tsconfig.base.json and configs for e2e, API tests and utilities that inherit it through extends and set types and include themselves:
This is exactly inheritance of settings. Project references (references and composite) are needed for something else, a linked build of several projects.
Common mistakes.
process.env.X! scattered across tests: a missing variable shows up far from the cause.
Extending ProcessEnv instead of checking: the type claims string although the variable may be missing.
Number(process.env.TIMEOUT_MS) without a default: an empty variable gives NaN or 0.
A file with declare module 'lib' that has an import: this is an augmentation, not a declaration, and the compiler complains the module cannot be found.
Secrets in a .env in the repository: the file goes in .gitignore and in CI they are set as secrets.
Check yourself
Why does extending ProcessEnv through declare global not protect against failing with undefined in a URL?
Answer
It is only a claim for the compiler and nothing is checked at runtime. If the variable is missing the value is still undefined while the type promises string. The check has to be written in code: a required function or a schema.
A custom global.d.ts contains declare global { interface Window { appReady?: boolean } } but window.appReady is still not found. What to check?
Answer
First, whether the file is a module (export {} is needed, otherwise declare global is not allowed), second, whether it falls into the tsconfig include, third, whether the project includes the DOM library (lib) that has Window.
Related lessons: “tsconfig for a test project”, “ES Modules and CommonJS”, “any, unknown and never”.
In an interview.Junior:.d.ts files contain only types. process.env is string | undefined, so I read variables through a module that checks them and fails with a clear message if one is missing. Middle/Senior: I do not extend ProcessEnv and do not use ! because that removes undefined without a check. I validate with a schema (zod) that also converts types. For different parts of a repository I make separate tsconfigs through extends with their own types, and I remember skipLibCheck as the reason errors in my own .d.ts files may go unnoticed.