Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

TypeScript TS2580: Cannot find name 'require'

TS2580 means no Node types are loaded. Install @types/node, set the types option, and check module mode, tsconfig inheritance and hoisting.

~5 min readTypeScript
#typescript#ts2580#types-node#compiler-errors
TypeScript TS2580 error card blocking a require call with a missing types crate beside it

Introduction & Quick Summary

A small TypeScript file that works at runtime refuses to compile:

code
src/server.ts:3:16 - error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`. 3 const path = require("path"); ~~~~~~~

Quick answer: the compiler has no Node.js type declarations in scope, so require, process, Buffer and __dirname are unknown identifiers. Install the types and let them load:

bash
npm install --save-dev @types/node
jsonc
// tsconfig.json { "compilerOptions": { "module": "commonjs", "moduleResolution": "node10", "types": ["node"] } }

The code runs fine under node, because Node implements require; TypeScript only checks what its own type environment knows. The message also appears when @types/node is installed but excluded by a types array inherited from a base config, and when a CommonJS call sits in a file compiled as ESM.

This guide covers the resolution order TypeScript uses for global declarations, the tsconfig settings that decide whether @types/node participates, and fixes for monorepos, bundler setups and code that needs require inside an ES module.

Core Mechanics, Signatures & Reproducible Setup

TypeScript ships no Node.js globals. lib: ["es2022"] provides Promise, Map, JSON and the language's built-ins; require, module, exports, process, Buffer, setImmediate, __dirname and __filename come from @types/node, a separate package that declares them as ambient globals in the NodeJS namespace.

TypeScript loads ambient declaration packages from node_modules/@types/* automatically, but only through this order:

  1. The files and include entries are compiled.
  2. compilerOptions.types — if present, only those packages are loaded. An empty array loads none.
  3. Otherwise, every package directly under node_modules/@types (and under typeRoots, when set) is loaded.
  4. /// <reference types="node" /> in a file adds @types/node for the program regardless of the types array.

A minimal reproduction:

bash
mkdir ts2580 && cd ts2580 npm init -y npm install --save-dev typescript @types/node mkdir src cat > src/index.ts <<'TS' const fs = require("fs"); console.log(typeof fs.readFileSync, process.version); TS cat > tsconfig.json <<'JSON' { "compilerOptions": { "target": "es2022", "module": "commonjs", "moduleResolution": "node10", "strict": true, "outDir": "dist" }, "include": ["src"] } JSON npx tsc --noEmit

With @types/node installed and no types array, this compiles. Remove the package, add "types": [], or move the file into a project whose tsconfig extends a base config with "types": ["jest"], and TS2580 appears on the require line.

buffer, globals, module and process are separate declaration files inside @types/node, so one install fixes the whole set of globals at once.

Key Comparison Table

CauseWhat you seeCorrect fix
@types/node not installedTS2580 on every Node globalnpm i -D @types/node
types array omits "node"TS2580 even though the package existsadd "node" to the array
typeRoots points elsewhereTS2580 plus missing DOM or test typesinclude the default roots or the package root
module: "nodenext" in an ESM fileTS2580 plus ESM-only diagnosticsreplace require with import
Dependencies not installed in the workspaceTS2580 only in CI or in a fresh cloneinstall in that package, not the root
Editor uses another TypeScriptCLI compiles, editor shows TS2580select the workspace TypeScript version
compilerOptions entryDefaultEffect on Node globals
typesunset (load all @types)when set, only the listed packages load
typeRoots./node_modules/@typesreplaces the lookup roots entirely
modulecommonjs (legacy), esnext in bundler presetsdecides whether require is legal syntax
moduleResolutionnode10 or bundlermust be able to find the @types package
verbatimModuleSyntaxfalsekeeps import/require as written, so a stray require survives transpile
allowJs with checkJsfalseJS files get the same globals check
You want to writeUseRequires
CommonJS in .tsconst x = require("x")@types/node, module: "commonjs"
ESM import in .tsimport x from "x"esModuleInterop for CJS default imports
ESM import of a JSON fileimport data from "./d.json" with { type: "json" }resolveJsonModule, module: "nodenext"
require inside a real ESM filecreateRequire(import.meta.url)@types/node, module: "nodenext"

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. The install is right but the version is wrong

@types/node majors track Node majors. Pairing @types/node@16 with a Node 22 runtime type-checks against APIs that no longer behave the same way, and newer APIs appear missing:

bash
node -v # v22.14.0 npm ls @types/node # 22.x is the matching line npm install --save-dev @types/node@^22

2. A types array in a base config silently excludes node

This is the most common false TS2580. A shared config narrows the ambient set for speed, and every package that extends it inherits the restriction:

jsonc
// tsconfig.base.json { "compilerOptions": { "types": ["jest"] } }
jsonc
// packages/api/tsconfig.json { "extends": "../../tsconfig.base.json", "compilerOptions": { "types": ["jest", "node"] }, "include": ["src"] }

Check the effective value rather than the file you are looking at:

bash
npx tsc --showConfig | python3 -c 'import json,sys; print(json.load(sys.stdin)["compilerOptions"].get("types"))'

--showConfig prints the merged result, which also reveals a typeRoots inherited from a framework preset.

3. Monorepos, pnpm and hoisting

With npm and Yarn classic, one root node_modules/@types/node serves every workspace. With pnpm's isolated store or Yarn PnP, a package that does not declare @types/node cannot see it:

bash
pnpm --filter @acme/api add -D @types/node # or, if the whole workspace needs it pnpm add -Dw typescript @types/node

The symptom is specific: a build at the repository root succeeds while the same command inside the package fails with TS2580, because the resolution root changed.

4. ES modules should not call require

When module is nodenext and package.json has "type": "module", a .ts file is ESM and require is not defined there — Node throws ReferenceError: require is not defined in ES module scope at runtime even if types are present:

ts
// src/config.ts, ESM import { readFileSync } from "node:fs"; // correct const text = readFileSync(new URL("./c.json", import.meta.url), "utf8");

Use the node: prefix so bundlers and linters agree that this is a built-in module, and use import.meta.url where CJS would have used __dirname:

ts
import { fileURLToPath } from "node:url"; const here = fileURLToPath(new URL(".", import.meta.url));

5. When require is genuinely needed in ESM

Some packages only expose CommonJS entry points, or a plugin needs a synchronous load that import() cannot provide. createRequire restores it without pretending the file is CommonJS:

ts
import { createRequire } from "node:module"; const require = createRequire(import.meta.url); const legacy = require("some-cjs-only-package"); const pkg = require("./package.json") as { version: string };

createRequire returns a typed function from @types/node, so TS2580 disappears only when the type package is actually loaded — in this shape the error means the ambient types are missing, not that the call is wrong.

6. Config files and test runners

vite.config.ts, jest.config.ts, playwright.config.ts and tailwind.config.ts are compiled by their own toolchain, often with a different tsconfig or none at all. A TS2580 in vite.config.ts while src compiles cleanly means the config file is outside the project's include:

{ "include": ["src", "vite.config.ts", "tests"], "compilerOptions": { "types": ["node", "vitest/globals"] } }

A separate tsconfig.node.json referenced from the root config is the tidier pattern for build tooling. The JSON formatter is handy here: paste the merged --showConfig output and confirm types, module and moduleResolution before changing anything, and the text diff tool shows which line a framework preset added.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Installing @types/node at the wrong level. A root install does not reach an isolated workspace; install in the package that compiles the file.
  • Adding // @ts-ignore above the line. It hides TS2580 but leaves the runtime behaviour unchecked, and the same global fails on the next line.
  • Declaring require by hand. declare const require: any compiles and destroys type safety for every module loaded through it.
  • Assuming a newer TypeScript fixes it. Resolution rules for nodenext became stricter in 4.7, so upgrades can introduce TS2580 in files that mixed require into ESM.
  • Editors and CLI disagree. VS Code can use its bundled TypeScript while npx tsc uses the workspace version; select the workspace version before debugging further.
  • Node 22 require(esm). Node can now require() some ES modules, but the type-level rule is unchanged: in a .ts file the compiler still needs @types/node, and in a "type": "module" package you still write import.

Official documentation: TypeScript types compiler option and Node.js modules: CommonJS and ESM.

Official references

primary documentation

The TypeScript documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.