Last updated: Feb 28, 2024
Reading timeยท2 min
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, use declare var require: any
to declare
require
as a global variable in your project.
Make sure you have the typings for Node.js installed.
Open your terminal in the root directory of your project (where your
package.json
file is) and run the following command.
npm i -D @types/node yarn add -D @types/node
If the error is still not resolved, try restarting your IDE.
If the error persists, make sure the types
array in your
tsconfig.json file contains "node"
.
{ "compilerOptions": { "types": [ // ... your other types "node" ], }, }
That should fix the error in your project.
require
as a global variable at the top of the fileIf that also didn't help, try declaring require
as a
global variable at the top of the
file where it's used.
declare var require: any
The declare var syntax is used to declare a global variable.
You should now also be able to use the process
global object.
const DB_PASSWORD = process.env.DB_PASSWORD;
I've written a detailed article on how to define types for process.env in TypeScript.
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.
# ๐๏ธ (Windows) delete node_modules and package-lock.json rd /s /q "node_modules" del package-lock.json del -f yarn.lock # ๐๏ธ (macOS/Linux) delete node_modules and package-lock.json rm -rf node_modules rm -f package-lock.json rm -f yarn.lock # ๐๏ธ clean npm cache npm cache clean --force npm install
Make sure to restart your code editor and development server if the error persists.
VSCode often glitches and needs a reboot.
require
syntax to ES ModulesIf that also doesn't solve your issue, you can try converting the require
syntax to ES6 modules import syntax.
// ๐๏ธ 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, use relative paths.
// ๐๏ธ default import import myFunction from './my-module'; // ๐๏ธ named import import { myFunction } from './my-module';
Generally, you should stick to using the 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.
Installing the typings for Node.js should also resolve the "Cannot find name 'process'" error in TypeScript.
npm i -D @types/node
Now you should be able to use the process
global object.
const DB_PASSWORD = process.env.DB_PASSWORD;
If the error persists, try restarting your IDE.