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.
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.
The most common fix is to install the Node.js type definitions package:
Install @types/node as a dev dependency:
npm install --save-dev @types/nodeOr with Yarn:
yarn add --dev @types/nodeOr with pnpm:
pnpm add --save-dev @types/nodeVerify the installation:
npm list @types/nodeAfter 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.
Even after installing @types/node, you may need to explicitly add it to your TypeScript configuration:
Edit tsconfig.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():
{
"compilerOptions": {
"types": ["jest"] // This restricts types to ONLY jest, excluding node!
}
}Solution - add node:
{
"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.
Ensure your tsconfig.json is configured for Node.js environments:
For CommonJS projects (using require):
{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"lib": ["es2020"],
"moduleResolution": "node",
"types": ["node"]
}
}For ES Modules projects (using import):
{
"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.
If your project supports it, consider migrating from require() to ES6 import syntax:
Convert require to import:
Old CommonJS style:
const express = require('express');
const fs = require('fs');
const app = express();
const data = fs.readFileSync('./file.txt', 'utf-8');New ES6 style:
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:
{
"compilerOptions": {
"target": "es2020",
"module": "esnext",
"moduleResolution": "node",
"types": ["node"]
}
}Update package.json (if not already):
{
"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.
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:
rm -rf node_modules package-lock.json
npm installClear TypeScript cache:
# Remove TypeScript build cache
rm -rf .tsbuildinfo
# For monorepos, might be in different locations
find . -name "*.tsbuildinfo" -deleteAfter restarting, TypeScript should recognize the types from @types/node and the error should disappear.
After fixing the compile-time error, ensure require() actually works when your code runs:
Check your execution context:
// This works in Node.js
const path = require('path');
// But NOT in browsers or bundlers without special setup
// Browsers don't have require() at allFor 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:
// ❌ 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():
// ❌ 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.
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:
{
"compilerOptions": {
"esModuleInterop": true
}
}This allows importing CommonJS modules like:
import express from 'express'; // CommonJS moduleInstead of:
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:
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.
Function expression requires a return type
Function expression requires a return type
Value of type 'string | undefined' is not iterable
How to fix "Value is not iterable" in TypeScript
Type 'undefined' is not assignable to type 'string'
How to fix "Type undefined is not assignable to type string" in TypeScript
Type narrowing from typeof check produces 'never'
How to fix "Type narrowing produces never" in TypeScript
Type parameter 'T' has conflicting constraints
How to fix "Type parameter has conflicting constraints" in TypeScript