Fix - Cannot find name 'require' Error in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 13, 2022

banner

Photo from Unsplash

Fix - Cannot find name 'require' Error in TypeScript #

To solve the "Cannot find name require" error, install the node types by running npm i -D @types/node. If the error is not resolved, you can use declare var require: any to declare require as a global variable in your project.

cannot find name require

The first thing you need to do is make sure you have typings for Node.js installed. Open your terminal in the root directory of your project and run the following command.

shell
npm i -D @types/node

If the error is still not resolved, try restarting your IDE.

If that doesn't help, make sure the types array in your tsconfig.json file contains "node".

tsconfig.json
{ "compilerOptions": { "types": [ // ... your other types "node" ], }, }

That should fix the "Cannot find name 'require'" error in your project.

If that also didn't help, try declaring require as a global variable at the top of the file where it's used.

index.ts
declare var require: any

The declare var syntax is used declare a global variable.

If the error is not resolved, try to delete your node_modules and package-lock.json files, re-run npm install and restart your IDE.

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

Make sure to restart your IDE if the error still persists. VSCode glitches often and a reboot solves things sometimes.

If that also doesn't solve your issue, you can try converting the require syntax to ES6 modules import syntax.

index.ts
// 👇️ default import import myFunction from 'some-module'; // 👇️ named import import { myFunction } from 'some-module';

The first example shows how to import a default export, and the second - a named export.

If you are trying to import one of your own, local files, you should use relative paths.

index.ts
// 👇️ default import import myFunction from './my-module'; // 👇️ named import import { myFunction } from './my-module';

Generally, you should stick to using ES6 modules import / export syntax when working in TypeScript. Once your code is compiled, it will still be converted to an older, more widely supported syntax.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.