Cannot find name 'URL' error in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 13, 2022

banner

Photo from Unsplash

Cannot find name 'URL' error in TypeScript #

To solve the "Cannot find name URL" error, make sure to add the DOM string to the lib array in your tsconfig.json file if running in the browser, or install typings for node if running in Node.js. You can import the module as import { URL } from 'url'.

cannot find name url

If you're running in the browser, make sure to add the DOM string to your lib array in tsconfig.json.

tsconfig.json
{ "compilerOptions": { "lib": [ "es2017", "DOM" ], // ... your other settings } }

The DOM type definitions are needed for programs that run in a browser.

If you are running in Node.js, make sure to install the typings for Node, by opening your terminal in the root directory of your project and running the following command.

shell
npm i -D @types/node

Your error should be resolved if your runtime is Node.js.

If it is not, make sure the types array in your tsconfig.json file contains "node".

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

You should be able to import and use the URL module in the following way:

index.ts
import { URL } from 'url'; const url = new URL('https://example.com'); console.log(url.host); // 👉️ "example.com"

This should fix the "Cannot find name 'URL'" error.

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 persists. VSCode glitches often and a reboot solves things sometimes.

Conclusion #

To solve the "Cannot find name URL" error, make sure to add the DOM string to the lib array in your tsconfig.json file if running in the browser, or install typings for node if running in Node.js. You can import the module as import { URL } from 'url'.

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.