Cannot find module axios - compatibility issue with typescript

Viewed 4321

I installed Axios local to my Typescript project, but generate an error when trying to import it. Error: "Cannot Find module axios".

root folder

npm install --save-dev axios

src/app.ts

import axios from 'axios';

package.json

 "devDependencies": {
    "axios": "^0.21.1",

It has something to do with my tsconfig.json. If I remove this file, axios is known. If I restore this file, the error comes back in VS Code. I know for Lodash package there is a Lodash types (https://www.npmjs.com/package/@types/lodash) to make lodash compatible with typescript. Is there an equivelent for axios?

I have this file .\node_modules\axios\index.d.ts that is supposed to help me out with typescript compatibility. Somehow it's not working.

3 Answers

This seems to help. It lets TS understand Axios. Even though Axios was supposed to work out of the box.

npm install --save @types/axios

suggestion - use: npm install --save axios instead

--save-dev flag is for those packages that are not part of your app and needed for development purposes such as running tests, transpiling, compiling code etc.

However --save-dev should have been work:

  1. check if node_modules/axios folder exists.
  2. try rm -rf node_modules and run npm install again

I had the same error in my http.ts file.

import axios, { Method, AxiosResponse } from 'axios';

const api = axios.create({
    baseURL: process.env.HOST_BACKEND,
  });
  
  const request = <T>(
    method: Method,
    url: string,
    params: any
  ): Promise<AxiosResponse<T>> => {
    return api.request<T>({
      method,
      url,
      params,
    });
  };
  
  export default request;

It happens because of typescript usage. I resolved by reinstalling axios npm package using @types/ like below

npm install --save @types/axios
Related