Solve - Cannot find module 'axios' Error in TypeScript

avatar

Borislav Hadzhiev

Sat Feb 19 20222 min read

banner

Photo by Drif Riadh

Solve - Cannot find module 'axios' Error in TypeScript #

To solve the "Cannot find module axios or its corresponding type declarations" error, install the module by running the command npm install axios. You can then import axios with the following line of code import axios from 'axios'.

cannot find module axios

Make sure to install the axios module, by opening your terminal in your project's root directory and running the following command:

shell
npm install axios

The axios module includes TypeScript definitions, so you don't have to install the types separately.

Now you should be able to import the axios module with the following line of code.

index.ts
import axios from 'axios'; console.log(axios);
This should fix the error and now TypeScript should be able to find the type definitions for the axios module.

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 you want to read more about making HTTP requests with axios in TypeScript, check out my other article - Making Http requests with Axios in TypeScript.

Here is an example of making an HTTP GET request with axios using TypeScript.

index.ts
import axios from 'axios'; type User = { id: number; email: string; first_name: string; }; type GetUsersResponse = { data: User[]; }; async function getUsers() { try { // 👇️ const data: GetUsersResponse const { data, status } = await axios.get<GetUsersResponse>( 'https://reqres.in/api/users', { headers: { Accept: 'application/json', }, }, ); console.log(JSON.stringify(data, null, 4)); // 👇️ "response status is: 200" console.log('response status is: ', status); return data; } catch (error) { if (axios.isAxiosError(error)) { console.log('error message: ', error.message); return error.message; } else { console.log('unexpected error: ', error); return 'An unexpected error occurred'; } } } getUsers();

You can read more about how to use axios with TypeScript by checking out my other article - Making Http requests with Axios in TypeScript.

Use the search field on my Home Page to filter through my more than 1,000 articles.