How to fix Cannot find name 'require' in TypeScript

TypeScriptBEGINNERMEDIUMUpdated Dec 8, 2025· 154 views

This TypeScript error occurs when you try to use the require() function without proper type definitions. The fix involves installing @types/node, configuring your tsconfig.json, or switching to ES6 imports depending on your project setup.

Quick fix

Fixes TS2304

npm install --save-dev @types/node
  1. Install @types/node package
  2. Add 'node' to types in tsconfig.json
  3. Configure lib and module in tsconfig.json
  4. Switch to ES6 imports (recommended for modern projects)
typescript — error
npm install --save-dev @types/node
Cannot find name 'require'
shell
npm install --save-dev @types/node

What this error means

The "Cannot find name 'require'" error in TypeScript indicates that the TypeScript compiler doesn't recognize the require() function, which is a CommonJS module syntax used in Node.js. This happens because TypeScript doesn't have type definitions for the Node.js global objects like require, module, and exports. By default, TypeScript assumes you're writing code for the browser (DOM environment) where require() doesn't exist. The require() function is specific to Node.js and CommonJS, so TypeScript needs explicit type definitions to understand it. This is a compile-time error, not a runtime error. Your code will fail type checking before it even runs. The error message appears as "TS2304: Cannot find name 'require'" in your IDE or when running the TypeScript compiler. The fix depends on your project structure: if you're using Node.js with CommonJS, you need @types/node. If you're building for modern environments, you should switch to ES6 imports. If you're in a browser environment, you shouldn't be using require() at all.

Typical symptoms

  • TypeScript compiler shows 'TS2304: Cannot find name 'require'' error
  • IDE highlights require() in red with squiggly underlines
  • Error appears in files that import or use require()
  • The error occurs even though require() works fine at runtime
  • module and exports are also reported as missing
  • __dirname and __filename cause similar errors
  • Error appears specifically in .ts files but not .js files

Common causes

  1. @types/node package is not installed in your project
  2. 'node' is not included in the types array in tsconfig.json
  3. Your TypeScript is configured for browser/DOM environment instead of Node.js
  4. tsconfig.json has a very restrictive types setting that excludes Node.js types
  5. Node.js global types are being suppressed by compiler options
  6. Using CommonJS (require) in an ES Modules-only project
  7. IDE is not picking up type definitions even though they're installed

How to fix "Cannot find name 'require'"

1Install @types/node package

The most common fix is to install the Node.js type definitions package:

Install @types/node as a dev dependency:

bash
npm install --save-dev @types/node

Or with Yarn:

bash
yarn add --dev @types/node

Or with pnpm:

bash
pnpm add --save-dev @types/node

Verify the installation:

bash
npm list @types/node

After installation, the TypeScript compiler will have access to the type definitions for require() and other Node.js globals. Your IDE should immediately recognize require() and the red squiggles should disappear.

Note: @types/node is a "dev" dependency because it's only needed during development/compilation. The types are not included in your production bundle.

2Add 'node' to types in tsconfig.json

Even after installing @types/node, you may need to explicitly add it to your TypeScript configuration:

Edit tsconfig.json:

json
{
  "compilerOptions": {
    "target": "es2020",
    "module": "commonjs",
    "lib": ["es2020"],
    "types": ["node"],
    // ... other options
  }
}

The "types" array tells TypeScript which type definitions to include. By default (when not specified), TypeScript includes all installed @types packages. However, if you have explicitly set a "types" array with other values, you must include "node" to get Node.js types.

Example of restrictive types that breaks require():

json
{
  "compilerOptions": {
    "types": ["jest"]  // This restricts types to ONLY jest, excluding node!
  }
}

Solution - add node:

json
{
  "compilerOptions": {
    "types": ["node", "jest"]  // Now both node and jest types are available
  }
}

After updating tsconfig.json, restart your IDE or TypeScript language server for changes to take effect.

3Configure lib and module in tsconfig.json

Ensure your tsconfig.json is configured for Node.js environments:

For CommonJS projects (using require):

json
{
  "compilerOptions": {
    "target": "es2020",
    "module": "commonjs",
    "lib": ["es2020"],
    "moduleResolution": "node",
    "types": ["node"]
  }
}

For ES Modules projects (using import):

json
{
  "compilerOptions": {
    "target": "es2020",
    "module": "esnext",
    "lib": ["es2020"],
    "moduleResolution": "node",
    "types": ["node"]
  }
}

Key options explained:
- module: "commonjs" for require(), "esnext" for import/export
- moduleResolution: "node" to use Node.js module resolution algorithm
- lib: Defines the built-in types available (es2020 is modern)
- types: Includes Node.js type definitions

The lib option affects built-in globals. If you omit "lib" entirely, TypeScript defaults to the DOM, which doesn't include Node.js globals.

4Switch to ES6 imports (recommended for modern projects)

If your project supports it, consider migrating from require() to ES6 import syntax:

Convert require to import:

Old CommonJS style:

typescript
const express = require('express');
const fs = require('fs');

const app = express();
const data = fs.readFileSync('./file.txt', 'utf-8');

New ES6 style:

typescript
import express from 'express';
import fs from 'fs';

const app = express();
const data = fs.readFileSync('./file.txt', 'utf-8');

Update tsconfig.json for ES modules:

json
{
  "compilerOptions": {
    "target": "es2020",
    "module": "esnext",
    "moduleResolution": "node",
    "types": ["node"]
  }
}

Update package.json (if not already):

json
{
  "type": "module"
}

ES6 imports are the modern standard and work in Node.js 12+. They're also what browsers natively support, making your code more compatible with different environments.

5Clear cache and restart TypeScript server

Sometimes the error persists even after fixes due to caching:

For VS Code:
1. Press Ctrl+Shift+P (or Cmd+Shift+P on Mac)
2. Type "TypeScript: Restart TS Server"
3. Press Enter

Or reload the window:
1. Press Ctrl+Shift+P
2. Type "Developer: Reload Window"
3. Press Enter

For other editors:
- Restart your IDE completely
- Delete node_modules and reinstall:

bash
rm -rf node_modules package-lock.json
npm install

Clear TypeScript cache:

bash
# Remove TypeScript build cache
rm -rf .tsbuildinfo

# For monorepos, might be in different locations
find . -name "*.tsbuildinfo" -delete

After restarting, TypeScript should recognize the types from @types/node and the error should disappear.

6Verify require() is available at runtime

After fixing the compile-time error, ensure require() actually works when your code runs:

Check your execution context:

typescript
// This works in Node.js
const path = require('path');

// But NOT in browsers or bundlers without special setup
// Browsers don't have require() at all

For browser environments:
If you're building for browsers, you cannot use require() at all. You must use ES6 imports and a bundler like Webpack or Rollup:

typescript
// ❌ Won't work in browsers
const _ = require('lodash');

// ✅ Works in browsers with proper bundler
import _ from 'lodash';

For Node.js with ES Modules:
If using "type": "module" in package.json, you must use import/export, not require():

typescript
// ❌ Error: require is not defined
const express = require('express');

// ✅ Correct for ES Modules
import express from 'express';

For monorepos or build systems:
Ensure your build tool (esbuild, swc, vite, etc.) is configured to handle the module format you're using.

Advanced notes

Understanding require() and TypeScript:

require() is a Node.js function that implements CommonJS, a synchronous module system. TypeScript, being a superset of JavaScript, inherits both CommonJS and ES6 module support. The issue is that TypeScript assumes it's running in a generic JavaScript environment by default.

When you use require() in TypeScript, the compiler needs to know:
1. That require() is a valid global function (from @types/node)
2. That you're targeting Node.js environment (via lib and types in tsconfig.json)

Module Systems Explained:

- CommonJS (require/module.exports): Synchronous, Node.js native, works in older Node versions
- ES Modules (import/export): Asynchronous, browser-native, modern standard, Node.js 12+

The error only happens with CommonJS require(), not with ES6 imports, because browser/generic environments don't provide require().

When to Use Each:

- Use require(): Legacy codebases, projects that must support Node.js < 12, or when you have strict runtime requirements for synchronous loading
- Use import/export: New projects, modern Node.js (12+), browser-compatible code, or when you need better tree-shaking

ES Module Interop:

The esModuleInterop compiler option helps when mixing CommonJS and ES modules:

json
{
  "compilerOptions": {
    "esModuleInterop": true
  }
}

This allows importing CommonJS modules like:

typescript
import express from 'express';  // CommonJS module

Instead of:

typescript
import * as express from 'express';

IDE Type Inference:

Even if your tsconfig.json is correct, your IDE might show errors if:
- node_modules/@types/node is missing or corrupted
- IDE hasn't reindexed changes
- Multiple tsconfig.json files with different settings (monorepos)
- IDE plugin/extension is out of date

Always restart your IDE's TypeScript server after dependency changes.

Build vs Runtime:

This error is purely a build/compilation issue. If you somehow bypass the compiler and run the code with Node.js directly, it would work fine because Node.js provides require(). The error message "Cannot find name 'require'" means the TypeScript compiler can't find it, not that it doesn't exist at runtime.

Type Declarations for require:

The type definitions from @types/node include:

typescript
declare function require(id: string): any;
declare namespace require {
  function resolve(id: string): string;
  function cache: any;
}

These declarations tell TypeScript that require() is a valid function with specific overloads and properties. Without these declarations, TypeScript treats it as an undefined variable.

Frequently asked questions

What does "TS2304" mean?
js. js global objects like require, module, and exports. By default, TypeScript assumes you're writing code for the browser (DOM environment) where require() doesn't exist.
How do I fix "TS2304"?
This TypeScript error occurs when you try to use the require() function without proper type definitions. The fix involves installing @types/node, configuring your tsconfig.json, or switching to ES6 imports depending on your project setup.
What causes "TS2304"?
@types/node package is not installed in your project 'node' is not included in the types array in tsconfig.json Your TypeScript is configured for browser/DOM environment instead of Node.js
Is the "TS2304" error serious?
It is a medium-severity error — more of a blocker than a risk. The steps above resolve it.

Official resources & further reading