Repository: axios/axios (JavaScript)

Issue:
[1.0.0] TypeError: Cannot read properties of undefined (reading 'create')
#### Describe the bug

```
const client = axios.create()
                     ^

TypeError: Cannot read properties of undefined (reading 'create')
    at Object.<anonymous> (/Users/rob/Developer/Personal/full-feed/test.js:5:22)
    at Module._compile (node:internal/modules/cjs/loader:1149:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1203:10)
    at Module.load (node:internal/modules/cjs/loader:1027:32)
    at Module._load (node:internal/modules/cjs/loader:868:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47

Node.js v18.10.0
```

#### To Reproduce

```js
#!/usr/bin/env node

const axios = require('axios').default

const client = axios.create()
  ```

#### Expected behavior
Runs without error.

#### Environment
 - Axios 1.0.0
 - Node.js 18.10.0
 - macOS Monterey 12.6

#### Additional context/Screenshots
* 0.27.2: runs without error
* 1.0.0: `TypeError: Cannot read properties of undefined (reading 'create')`

(I could not see any breaking change)

Exported classes in type definition are not actually exported
<!-- Click "Preview" for a more readable version --

Please read and follow the instructions before submitting an issue:

- Read all our documentation, especially the [README](https://github.com/axios/axios/blob/master/README.md). It may contain information that helps you solve your issue.
- Ensure your issue isn't already [reported](https://github.com/axios/axios/issues?utf8=%E2%9C%93&q=is%3Aissue).

⚠️👆 Feel free to these instructions before submitting the issue 👆⚠️
-->

#### Describe the bug
`AxiosHeaders`, `AxiosError`, `CanceledError`  and `Axios` are "exported" in the type definitions `index.d.ts`, but not exported in the module.

#### To Reproduce

```ts
const { AxiosHeaders } = require('axios');  // Allowed by Typescript

const headers = new AxiosHeaders({ 'name': 'value' }); // <-- throws Error as AxiosHeaders is not actually exported
```

#### Expected behavior

~~Types are not exported, but only declared (`declare class` instead of `export class`).~~

Classes are exported and can be imported and used like so:
```ts
import { AxiosError, AxiosHeaders, Axios, CanceledError } from 'axios';

new AxiosError();
new AxiosHeaders();
new Axios();
new CanceledError();
```

#### Environment
 - Axios Version 1.1.0
 - Node.js Version 16.15.1
 - OS: OSX 12.5
 - Typescript 4.6.3 (any version)
 - React 17

#### Additional context/Screenshots
none

🐛 [BUG] - TypeError: axios.defaults is undefined in v 1.1.0
## Description

I use CDN with `https://unpkg.com/axios/dist/axios.min.js` without specify version in my project, and before new version release, I can work it well.
But after new version release, it will show the error:

```
TypeError: axios.defaults is undefined
```

I tried to find some release notes or upgrade guide but I saw someone find them too, so I rollback to old version, and it works now!
But I have several pages needs to rollback the version 😢 

Is rollback version only way to fix this error?

## Code

I used axios with Vue.js, and this is the part in my Vue app:

```javascript
getProjectSec: function (token) {
    axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
    // ^^^^^ Uncaught (in promise) TypeError: axios.defaults is undefined

    this.projects(project => {
        axios({
            url: `api/Project/${project.value}`,
            method: 'get',
        }).then(res => {
            // Do something
        }).catch(err => {
            console.log(err.response);
        })
    })
}
```
Typescript imports not working
I am importing axios as follows into my typescript project:
```
import axios from 'axios';
```
which compiles without a problem, however the resulting javascript code throws an exception.
![image](https://user-images.githubusercontent.com/2115696/194818062-724bab98-92cb-4e36-a95c-3868f5e3d57e.png)
If I change my import to:
```
import * as axios from 'axios';
```
I get a compiler error:
![image](https://user-images.githubusercontent.com/2115696/194818485-b31a4b35-4fb5-4b33-90c6-e4d5b50664fc.png)
But at least the resulting javascript code runs without issues.

Seems like there's kind of a mismatch here.
require not supported after upgrading to axios 1.1.2
we are getting below error after upgrading axios to the 1.1.2 version

2022-10-11T04:56:57.575682812Z stderr F Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /app/node_modules/axios/package.json.
--
  |   | 2022-10-11T04:56:57.575671912Z stderr F require() of /app/node_modules/axios/index.js from /app/server.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
  |   | 2022-10-11T04:56:57.575663912Z stderr F require() of ES modules is not supported.
  |   | 2022-10-11T04:56:57.575654512Z stderr F Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /app/node_modules/axios/index.js
  |   | 2022-10-11T04:56:57.575647612Z stderr F
  |   | 2022-10-11T04:56:57.575640211Z stderr F       ^
  |   | 2022-10-11T04:56:57.575628111Z stderr F       throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
  |   | 2022-10-11T04:56:57.575556611Z stderr F internal/modules/cjs/loader.js:1172



 - Axios Version 1.1.2

 - Node.js Version 12


After upgrading form v0.27.2 to v1.1.2 import error with Vite
#### Summary

In Vue3 / TypeScript project,
import { AxiosError } from 'axios';

Build shows warning:
Non-existent export 'AxiosError' is imported from node_modules/axios/index.js

Although there is only a build warning, any component (Vue) or TypeScript (ts) that includes this import fails to work.
Browser console (Dev-Tools) shows:

Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/axios.js?v=3226fa61' does not provide an export named 'AxiosError' (at auth-store.ts:2:17)

#### Environment
 - Axios Version 1.1.2
 - Node.js Version v17.4.0
 - OS: Windows 10
 - Vite version: 3.1.7

`1.1.3` probably broken
### Describe the bug

I think there are issues is exporting the axios object and also a issue when in get function when in the instance of Axios class.


### To Reproduce

Install
- Axios `V1.1.3`
- Node `v18.4.0`


### Code snippet

```js
const { Axios, default: a } = require('axios');

const ax = new Axios();

a.get("https://www.eldorado.gg/buy-wow-gold/g/0-0-0").then(x => console.log(x.data))

ax.get("https://www.eldorado.gg/buy-wow-gold/g/0-0-0").then(x => console.log(x.data))
```


### Expected behavior

This code should have logged the data (html) from that url.
Mainly the issue is that default export is undefined.

### Axios Version

`>1.1.0`

### Adapter Version

_No response_

### Browser

_No response_

### Browser Version

_No response_

### Node.js Version

18.4.0

### OS

Windows 10

### Additional Library Versions

_No response_

### Additional context/Screenshots

```bash
There were bugs like
1. In default export, that is undefined. [Image](https://media.discordapp.net/attachments/723104565708324915/1031017046743461928/unknown.png)

2. `Axios`'s instance's get function have a bug as well. [Image](https://media.discordapp.net/attachments/723104565708324915/1031017137382363336/unknown.png)

I tested old versions and for me version `1.1.0` and earlier versions are working fine.
```

axios 1.1.3 can't use in a library
### Describe the issue

Hi, i've created a library and it was working fine, but after the update to 1.1.3 it started to give me a bunch of the following error :
"BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
        - install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "stream": false }","

I'm currently using 1.1.2 and it's working fine, but since i'm not the only one that uses the library, i'm afraid of this issue, how can i fix this? i already tried to upgraded the version of both(library and project) to 1.1.3 and doesn't work, the only thing that worked for me until now was setting everything back to 1.1.2. Help!
 

### Example Code

_No response_

### Expected behavior

_No response_

### Axios Version

1.1.3

### Adapter Version

_No response_

### Browser

_No response_

### Browser Version

_No response_

### Node.js Version

_No response_

### OS

_No response_

### Additional Library Versions

```bash
angular 14.0.0
```


### Additional context/Screenshots

_No response_
ESLint no-named-as-default-member for isAxiosError
### Describe the bug

After upgrade to 1.1.3 my ESLint complains about `import/no-named-as-default-member`

![image](https://user-images.githubusercontent.com/13970783/196927145-1a5e81ec-d359-4b33-9cde-3e0556ab6e79.png)

But in reality, I cannot import as `import { isAxiosError } from 'axios';`

![image](https://user-images.githubusercontent.com/13970783/196927257-b540eb7e-60c5-4560-b880-f23bf890bfe2.png)

So something is broken with TS types


### To Reproduce

Turn on `import/no-named-as-default-member` ESLint rule, update axios to 1.1.3, try to use `axios.isAxiosError` and observe error.

### Code snippet

_No response_

### Expected behavior

I should be able to satisfy eslint and be able to import as `import { isAxiosError } from 'axios';`

### Axios Version

1.1.3

### Adapter Version

_No response_

### Browser

_No response_

### Browser Version

_No response_

### Node.js Version

_No response_

### OS

_No response_

### Additional Library Versions

```bash
xo 0.52.4
```


### Additional context/Screenshots

_No response_


Discussion:
Same issue with `get`:
```
/home/gui/sambashare/scripts/axios-test.js:4
  const res = await axios.get(`<url>`, {
                          ^

TypeError: Cannot read properties of undefined (reading 'get')
```

with:
```
const axios = require('axios').default
const main = async () => {
  await axios.get('<url>')
}
main()
```
That is a major breaking change
I am getting similar error

```
Uncaught TypeError: axios.create is not a function
    at eval (api.js:5:1)
```

My code is - instance:

```js
const axios = require('axios');
const { gateway } = require('../config/environment');
const { version } = require('../../package.json');

const api = axios.create({
  baseURL: gateway,
  headers: {
    'Content-Type': 'application/json; charset=UTF-8',
    'Cache-Control': 'no-cache',
    Pragma: 'no-cache',
    'X-Application-Name': 'app-name',
    'X-Application-Version': version
  }
});

api.interceptors.response.use(
  (response) => response.data,
  (error) => { throw error; }
);

module.exports = { api };
```

And request, for example:

```js
const { api } = require('../config/api');

const getSomeEndpoint = (data) => (
  api.post('endpoint', data)
);

module.exports = { getSomeEndpoint };
```

I am not sure where is the problem, I can't find it in my code 😞 
That's especially an issue since the document says to use `.default` [here](https://github.com/axios/axios#note-commonjs-usage)
> I am getting similar error
> 
> ```
> Uncaught TypeError: axios.create is not a function
>     at eval (api.js:5:1)
> ```
> 
> My code is - instance:
> 
> ```js
> const axios = require('axios');
> const { gateway } = require('../config/environment');
> const { version } = require('../../package.json');
> 
> const api = axios.create({
>   baseURL: gateway,
>   headers: {
>     'Content-Type': 'application/json; charset=UTF-8',
>     'Cache-Control': 'no-cache',
>     Pragma: 'no-cache',
>     'X-Application-Name': 'app-name',
>     'X-Application-Version': version
>   }
> });
> 
> api.interceptors.response.use(
>   (response) => response.data,
>   (error) => { throw error; }
> );
> 
> module.exports = { api };
> ```
> 
> And request, for example:
> 
> ```js
> const { api } = require('../config/api');
> 
> const getSomeEndpoint = (data) => (
>   api.post('endpoint', data)
> );
> 
> module.exports = { getSomeEndpoint };
> ```
> 
> I am not sure where is the problem, I can't find it in my code 😞

Yes, this form is functional,  but you don't have the helpers either the types. When you use default the method create return undefined, this is the reason of the error.
@gdelory, @Angros23 

With `.default` app is working correctly, but during the build it crashes.
I am using `gatsby` and during the build I do the first requests.
(I have build app without default, It passed, and then added default and reloaded, then was OK, but still when I try to build once again, the app not built) 😞 

```
gatsby-node.js: TypeError: Cannot read properties of undefined (reading 'create')
```

Before the upgrade to `1.0.0` it was working correctly without `default`.
Will look into this asap
> Will look into this asap

@jasonsaayman Thank you, I'm also checking, if it is not a problem with Gatsby. Tell me if there is something I can do to help 
See #5030 merged should fix this.
@jasonsaayman works like a dream, thank you!

Please stay on 1.1.0 for now i need to come up with a solution that works for both commonJS and ESM
Getting this error with Node.js

Import:
const axios = require('axios').default;

Error:
axios.defaults.withCredentials = true;
TypeError: Cannot read properties of undefined (reading 'defaults')

But really it's just erroring everywhere because 'axios' is not defined:
await axios.post(endpoint, params, config);
TypeError: Cannot read properties of undefined (reading 'post')

I rolled back with "npm install axios@0.27.2" and it works fine.
It looks like you don't need `.default` option anymore.
```javascript
const axios = require('axios');
const client = axios.create({ ...});
```

this ^ worked for me
@womprat for that the latest version should work if you drop the `.default`
I've noticed that...
```
import axios from 'axios';
```
...will reproduce this error, so you need to use:
```
const axios = require('axios');
```

Which is maybe something that should be fixed?
Removing `.default` will work fine but will cause TS errors
With 1.1.3 and TS, this code:
```typescript
import axios from 'axios';
const axiosClient = axios.create();
```

is transpiled to:
```javascript
const axios_1 = require("axios");
const axiosClient = axios_1.default.create();
```

and it fails.
@orgads thanks I will have a look
Same issue with `post`

looking for a solution for typescript users. require is still required

Works great if you put the past version.
> npm install axios@0.27.2
Same issue post, spent quite some time on this. Version 1.1.0 works fine though
To write a program I installed Axios with `npm install --save axios`, which installed v1.1.3, then in index.js I wrote some code using `axios.create`, and it seems Visual Studio code autocompleted the import statement for me to incorrectly be `const { default: axios } = require("axios");`, so when I ran my program I got error `[TypeError: Cannot read properties of undefined (reading 'create')`. To fix it I used the same version and just changed the line manually to simply `const axios = require("axios");`
I am also able to reproduce this issue via following method 

Sample TS Code
```
import axios from "axios

axios.get("http://some-api")
```

Now after compiling this code 
```
tsc my-code.ts
node my-code.js
```

We will get the following error 
``` 
Cannot read properties of undefined (reading 'get')
```

Now the only work around is to switch back to version 1.1.0

> I am also able to reproduce this issue via following method
> 
> Sample TS Code
> 
> ```
> import axios from "axios
> 
> axios.get("http://some-api")
> ```
> 
> Now after compiling this code
> 
> ```
> tsc my-code.ts
> node my-code.js
> ```
> 
> We will get the following error
> 
> ```
> Cannot read properties of undefined (reading 'get')
> ```
> 
> Now the only work around is to switch back to version 1.1.0

Same issue
Tried 1.1.0 and 1.1.3
```
import axios from axios
axios.create
```
Same issue here, `axios.create` results in `TypeError: Cannot read properties of undefined (reading 'create')`

Had to switch back to 1.1.0 - huge breaking change
following
For Node.js projects without TS, this hack will work fine.

```js
const axios = require('axios').default || require('axios')
```

The first `require()` let VSCode show autocomplete when typing, and the second one will be used at runtime.
> With 1.1.3 and TS, this code:
> 
> ```ts
> import axios from 'axios';
> const axiosClient = axios.create();
> ```
> 
> is transpiled to:
> 
> ```js
> const axios_1 = require("axios");
> const axiosClient = axios_1.default.create();
> ```
> 
> and it fails.

I have even tried to check using earlier version(0.27.1, 0.27.2, 1.0.0), looks like issue is still persits.
this is still an issue with version 1.1.3 on TypeScript. the Axios instance is being created but I get the following error
`TypeError: Cannot read properties of undefined (reading 'isAxiosError')`

when catching and testing an error message with 
`axios.isAxiosError(err)`

my simplified code is
```
import axios from 'axios'

try{
  const response = await axios.get(url);
  console.log(response.data);
}
catch (err){
  if (axios.isAxiosError(err)) {
     console.error(err.message)
   } else {
     console.error(err)
   }
}
```

Can confirm, still an issue with 1.1.3.  I thought I might be doing something dumb but ended up here by while searching. 
@kob490 @noseratio I don't believe this fix has been released yet. 1.1.3 is from several weeks ago.
+1 here
Update: changed to 1.1.0 and worked with 

import axios, { AxiosInstance } from 'axios';
this.axios = axios.create();

I think this is related to (and should be fixed by) #5174. The fix should be released soon.
I'm getting this error, not sure if it is related to this issue or not. 
```
import axios from 'axios'
axios({ url, baseURL, headers, method, data, params })
    .then(res => success(res))
    .catch(res => failure(res))
...

TypeError: Cannot read properties of undefined (reading 'toJSON')
    at index.ts:848:1
    at Array.forEach (<anonymous>)
    at Store.get (index.ts:847:1)
    at StateMethodsImpl.getUntracked (index.ts:1135:1)
    at StateMethodsImpl.get (index.ts:1171:1)
    at Object.get (index.ts:1421:1)
    at JSON.stringify (<anonymous>)
    at Object.onSet (Persistence.ts:20:1)
    at index.ts:1037:1
    at index.ts:978:1
```
@ianriosBAF
+1

Following the topic to know when it will be fixed
+1 same here with `1.1.3` TS->JS
Please try the latest pre-release and let me know `npm i axios@1.2.0-alpha.1`
> Please try the latest pre-release and let me know `npm i axios@1.2.0-alpha.1`

Seems to work for me

Thank you

Worked for me too, thanks!
> Please try the latest pre-release and let me know `npm i axios@1.2.0-alpha.1`

This works! 
try axios without .default it work version 1.1.3

```
return await axios
      .get(
        `${baseUrl}?fields=${process.env.Feed_Fields}&access_token=${process.env.fbAPI}&limit=10`,
        {
          headers: {
            Accept: "application/json",
          },
        }
      )
      .then(({ data }) => data);
```
> Please try the latest pre-release and let me know `npm i axios@1.2.0-alpha.1`

This works, thanks !
> npm i axios@1.2.0-alpha.1

This works for me, too. thanks.
> Please try the latest pre-release and let me know `npm i axios@1.2.0-alpha.1`

This worked for me as well on TS 4.6.4
If I install axios 1.2.1 that is currently available then I get tons of errors like this:

```
Argument of type 'import("./node_modules/axios/index").AxiosRequestConfig<any>' is not assignable to parameter of type 'import("./node_modules/@nestjs/axios/node_modules/axios/index").AxiosRequestConfig<any>'.
```

It seems that the version mismatch breaks it all.

Edit: whoops thought this was on the nestjs github. I guess I'll have to wait for that dependency to update to fix this then.
having this error- Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data')
    at Details.js:18:1
whille trying to axios and catch the data.json this way-
const ExcelExportData = [];
    let i = axios.get('https://localhost:44357/User').then(
        result => { ExcelExportData = result.data }
    )
        .catch(error => {
            console.error(error.response.data);
        })
> having this error

Which axios version?
Still getting this issue when trying compiling from TS to JS.
axios version 1.4.0
Any update on this?
Yeah, this isn't fixed on the latest version. Same behaviour as all the above (using Gatsby). ^0.21.1 worked then borked on an update to ^1 and I've tried everything above, so downgraded to ^0.21.
same problem here, pinned the version to v.1.2.2 for now

I guess that's a duplicate of #5004 
Issue not fixed: Classes are still not exported in the `index.js` file. Need to add something like `export * from './lib/axios.js';`
+1 I am getting this error with `1.1.2`

```
export 'AxiosError' (imported as 'AxiosError') was not found in 'axios' (possible exports: default)
```
Having the same issue with `CanceledError`:
```ts
import { CanceledError } from 'axios';

console.log(CanceledError); // undefined
```

And `error instanceof CanceledError` throws an error because `undefined` is not an object ¯\\\_(ツ)_/¯
Others like AxiosProgressEvent seem to be fine

As a workaround for now I used axios.AxiosError, so for example:

```typescript
if (error instanceof axios.AxiosError) {
```

got the idea from this ticket: https://github.com/axios/axios/issues/5062
Another workaround is the use of 'axios.isAxiosError'

Same here.  1.0.0 didn't have this problem, but #4999 was a show stopper for us.

In 1.1.0, I think this another problem introduced by #5030 

```
% yarn node
Welcome to Node.js v16.17.0.
Type ".help" for more information.
> const axios = require('axios')
undefined
> axios.defaults.baseURL = "https://www.google.com"
Uncaught TypeError: Cannot set properties of undefined (setting 'baseURL')
```
It looks like the default is no longer the default. As a workaround, you can explicitly use it; note the change in the `require` line below:
```
% yarn node
Welcome to Node.js v16.17.0.
Type ".help" for more information.
> const axios = require('axios').default
undefined
> axios.defaults.baseURL = "https://www.google.com"
'https://www.google.com'
```
Probably?
https://github.com/axios/axios/blob/9c3dce366bd594558e5e474ce9135af22a0d9949/dist/node/axios.cjs#L3760

We downgrade to @1.0.0. and it seems fine.
I think it's this commit: https://github.com/axios/axios/pull/5030/commits/819ad75564f472a9066fa4de3eaf416604daddc5 

![image](https://user-images.githubusercontent.com/24503523/194462325-a3994a81-bb06-46cb-98db-cb46f595c9bb.png)

Issue still persists even with release 1.1.2
axios.defaults.headers.common ,
facing the same issue: TypeError: Cannot read properties of undefined (reading 'defaults')

Fixed for me in 1.1.2.
Still facing the same issue with the 1.1.2 release.
For those following the CommonJS change suggested in README by adding `.default` in require, reverting back to `const axios = require('axios');`  _(removing `.default`)_ works for v1.1.2.
>  _(removing `.default`)_ works for v1.1.2.

It works, withouth TypeScript typings
It works with `axios = require('axios').default;` 🎉
This problem persist for me. For some reason, when compiling typescript to javascript, it adds a "default" after axios... and terminal is complaining that axios.default is undefined.
Example:
In index.ts I have: axios.request("my api")
When compiling I see in index.js:
axios.default.request("my api") and this fails with error :  TypeError: Cannot read property 'request' of undefined
Seriously... I've been fighting with this for 3 hours thinking I was messing up something
Any fix for this until the new version is released?
Not an ideal way to fix this but after compiling, remove ['default'] from where it's on any axios request and the compiled ['default']-free file will run properly.

Same issue here ;) Works in `1.1.0` but doesn't in `1.1.2`
@GabrielModog, yeah, that was the code we had in our codebase (as opposed to what @AuspeXeu has), but the results are the same. I believe something broke between the releases I mentioned.
@GabrielModog that's literally what the first code block in my issue description is ;)
If that's an option for you, a workaround is to enable [esModuleInterop](https://www.typescriptlang.org/tsconfig#esModuleInterop).
+1
+1

It doesn't work since v1.0.0 (0.27.2 works fine with the same codebase), importing axios results in an undefined variable.
Any idea what to do ?
> +1
> 
> It doesn't work since v1.0.0 (0.27.2 works fine with the same codebase), importing axios results in an undefined variable. Any idea what to do ?

It works in `1.1.0`, we are using that successfully.
@Enngage how about `1.1.2`?
I am having the same problem with the `1.1.2` and i cannot seem to make it work with `1.0.0` as well.
This seems to have been introduced in `1.1.1`. `1.1.0` is the last working version.
> This seems to have been introduced in `1.1.1`. `1.1.0` is the last working version.

Indeed, thanks for pointing that out. I have the issue both on `1.0.0` and `1.1.1`. However `1.1.0` is working fine. So do you think the bug may have been introduced, removed and reintroduced ?
@apt-bh yeah this is actually what happened. There is an oddity that has crept in with the build process and until we locked it down we mended common JS as this is by far the widest implementation of the library. I have merged a PR recently that I am going to test and hopefully that solves all issues for us with regard to this. Watch for a v1.1.3
> @apt-bh yeah this is actually what happened. There is an oddity that has crept in with the build process and until we locked it down we mended common JS as this is by far the widest implementation of the library. I have merged a PR recently that I am going to test and hopefully that solves all issues for us with regard to this. Watch for a v1.1.3

Thanks for the quick reply, I'll be watching for the new release 
I have done testing and this is now working plus the common JS use is working, I will do a release tonight
I just facing the same issue in typescript but I tried use ``  "axios": "^0.27.2",`` and working just fine 
v1.1.3 still not working
+1
> If that's an option for you, a workaround is to enable [esModuleInterop](https://www.typescriptlang.org/tsconfig#esModuleInterop).

**Solves it for me.** Though I had to change the syntax of other imports I have.
Same problem, I had to fall back to 1.1.0
+1
+1 having same issue
Problem persists in 1.1.3 for me
Facing this issue as well on 1.1.3. Any updates on this?

We have the same issue. 
Can you please send a snippet of the import in app/server.js
Hello :wave: a similar issue happens to me on a simple Nuxt 2 project.

> Must use import to load ES Module: /sandbox/node_modules/axios/index.js require() of ES modules is not supported. require() of /sandbox/node_modules/axios/index.js from /sandbox/node_modules/vue-server-renderer/build.dev.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /sandbox/node_modules/axios/package.json.

- Sandbox: https://codesandbox.io/s/peaceful-pare-lrvngu?file=/pages/index.vue
- Reproduction steps:
  1. Scaffold a [Nuxt 2](https://nuxtjs.org/) project
  2. Add `"axios": "^1.1.3"` as dependency
  3. Try importing `axios` from anywhere

Could be related: https://github.com/axios/axios/issues/5150
@amercier Did you find a temporary workaround to this problem? I'm getting the same issue today when trying to run `npm run generate` in my Nuxt 2 project.
I solve this problem by using the command: npm i axios@0.21.1

I think this problem is because the latest axios does not support require()
> Did you find a temporary workaround to this problem? I'm getting the same issue today when trying to run `npm run generate` in my Nuxt 2 project.

@sts-ryan-holton: No, no workaround for version 1.x so far I'm afraid.

> I solve this problem by using the command: npm i axios@0.21.1
> I think this problem is because the latest axios does not support require()

@yanheng888: Yes, also I can confirm `0.27.2` works great as well, I'd recommend using the latest `0.x` until this is fixed.
> I solve this problem by using the command: npm i axios@0.21.1
> 
> I think this problem is because the latest axios does not support require()

Thanks ! 
@amercier Thank you very much, it helped me a lot!
thanks.it was helpful for me to,but i want know the reason?

and how it can be fixed? 
Thanks @DigitalBrainJS @jasonsaayman

It has fixed using `require`.

The problem I'm having is that my project uses the [github.com/standard-things/esm](https://github.com/standard-things/esm) package.

When I try and run the module using `node -r esm index.js` I get this error:

```
Error [ERR_REQUIRE_ESM]: require() of ES Module .../test-axios/node_modules/axios/index.js not supported.
Instead change the require of index.js in null to a dynamic import() which is available in all CommonJS modules.
```

Using:
* axios@1.2.1
* esm@3.2.25
* Node 16.18.1

The index.js file only contains:

```
import axios from 'axios';
console.log(axios);
```

I have asked a question here too: https://stackoverflow.com/questions/75152442/error-err-require-esm-require-of-es-module-when-using-esm-package-with-ax

i fixed this error, only change  axios version  in Package.json in  my proyect: i had : 1.3.1 y change to 0.24.0, and run "npm i " again and work it
> Thanks @DigitalBrainJS @jasonsaayman
> 
> It has fixed using `require`.
> 
> The problem I'm having is that my project uses the [github.com/standard-things/esm](https://github.com/standard-things/esm) package.
> 
> When I try and run the module using `node -r esm index.js` I get this error:
> 
> ```
> Error [ERR_REQUIRE_ESM]: require() of ES Module .../test-axios/node_modules/axios/index.js not supported.
> Instead change the require of index.js in null to a dynamic import() which is available in all CommonJS modules.
> ```
> 
> Using:
> 
> * axios@1.2.1
> * esm@3.2.25
> * Node 16.18.1
> 
> The index.js file only contains:
> 
> ```
> import axios from 'axios';
> console.log(axios);
> ```
> 
> I have asked a question here too: https://stackoverflow.com/questions/75152442/error-err-require-esm-require-of-es-module-when-using-esm-package-with-ax

Hello, I met the same problem. Still a bit confused to me: How to resolve this problem? By "It has fixed using `require`", You mean just replacing the import by require in the source code when using axios?

Thanks a lot. 

Best regards, Jason
Hi, I too faced the similar issue even in latest v1.6.8, 
```
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/Github/test-axios/node_modules/axios/index.js not supported.
Instead change the require of index.js in null to a dynamic import() which is available in all CommonJS modules.
```
I was using `esm` so switching to `esm-wallaby` fixed my problems.

#5062 
Duplicate of #5031, possibly? I was having a similar issue with CanceledError.

Still problems with this in typescript. Using version 1.1.3 

TypeError: Cannot read properties of undefined (reading 'get')
I can't believe that this is an on-going problem for over a full week already.

Using v1.1.3, which is still broken, this doesn't work as well:

import axios from "axios";
TypeError: Cannot read properties of undefined (reading 'get')
For this use `import { Axios } from 'axios';`
Node v10.24.0 => Axios version 1.1.3 or 1.1.0

With : 
`const axios = require('axios');`

or

`const axios = require('axios').Axios;`

There's something fundamentally broken on this main version : 

import axios from './lib/axios.js';
_____^^^^^
 
SyntaxError: Unexpected identifier
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
@Zighy You're using an old version of node.
> @Zighy You're using an old version of node.

What is the minimum supported version of Node ?
@Zighy I can't speak officially for axios, but a quick test seems to say that node v12 should do the trick, but v12 has passed end of life date as well.
@ralphtheninja I am using v18, but the default export is not working for me.
And for using the axios class itself, I did used it but its get function was throwing some issue.
So for now I am just using a old version.
@KartikeSingh Have you tried the following with axios 1.1.3 (in node)?

```js
const axios = require('axios')
axios.get(/* .. */)
```
I can just give some background on how we're using `axios`. It's part of a custom module that we use in-house that's being used by _both_ node and the browser (react). The following seems to work well for both node and the browser:

```js
const AXIOS = require('axios')
const axios = AXIOS.default || AXIOS
axios.get(/* .. */)
```

Hope this helps.
hmm I see, seems like `default` is broken for node, I will try using `const axios = require('axios');` 

Edit:
yes the above method words, So I think they need to fix their typings.
Yes it is a typings problem, would be nice if someone could fix it so that we can start using the latest version
+1
Will be doing another release this week. Apologies for this not being very smooth, seems the upgrade to ESM was a lot rockier than previously expected.

You may want to look at you NodeJS version and what ES version you are targeting. It sounds like something is outdated in your tool chain?
It seems like the change of browser enrty with built cjs file affect more than expected?
When axios is used to create a library as above, the dist file can not be process with tool chain, while nodejs core modules (stream, https, etc) are not be polyfilled in dist cjs file... 

https://github.com/axios/axios/compare/v1.1.2...v1.1.3#diff-7ae45ad102eab3b6d7e7896acd08c427a9b25b346470d7bc6507b6481575d519R9 
![image](https://user-images.githubusercontent.com/8591672/196590661-7bdb1ecb-74a3-4730-bd1e-76f84d86b680.png)


Ok, will have to have a look can i be given the environment details NPM/Node versions etc
node v16.17.1 , it's a typescript library that i use in my angular projects, the version of Angular of my projects are all 14.0.0
Browsers use modules/or will transpile module maybe just add it "import": "./dist/esm/axios.js",?
I'd be concerned about needing to do a deep import of anything in a package.

@c4tc4tc4t Are you able to create a minimal Angular project that demonstrates the issue? It may be easier for other contributors to investigate based on this?
> https://github.com/c4tc4tc4t/axioslibtest
> 
> there u go @ajmas , make sure to install on a angular project to test, you can use the function checkImportStatus to test it, the error will occur when you run ng serve

I have never really worked with Angular, so I am not sure about the remaining recipe to be able to run this. I'd rather just focus at looking at the failure behaviour, since I don't have too much time on my hands.
ok, running some tests i found out that the problem is in the type AxiosResponseHeaders that comes from axios, did u guys change something with this type in this update?
still not figured out, acctually the lib that i created does not contain the error, my bad sry, but the actual lib i cant post it
i'll try to code a lib with the problem, now that i have a notion of what it is and a angularproject, so you guys can just clode the project and install the lib and have a better understading of what's going on, give me time to do it.
Ok, so what you have to do is create a Angular 14.0.0 project, then run "npm install https://github.com/c4tc4tc4t/poketeste" , i will install my typescript library that contains only one function, install axios in the Angular project and import the lib "import * as poke from 'axiosteste'", axiosteste is the name of my lib, try a console.log(poke.pokemon()); , if u run ng serve, you will get my error, waiting for some help on this, and of course if u change the version of axios on my lib and the project back to 1.1.2 everything works fine!
Well this changed
![image](https://user-images.githubusercontent.com/8037810/197388718-0c26b55f-02d4-45d5-942d-8477fae638c6.png)

Kinda destroyed what's use for browser and node platform because  

axios\dist\node\axios.cjs

Got this 
![image](https://user-images.githubusercontent.com/8037810/197388798-1ee599f7-7a33-4da3-ba34-9cc5b737f203.png)

And axios\dist\axios.js got this 
![image](https://user-images.githubusercontent.com/8037810/197388872-feeaf549-befd-4ead-8773-ab7720dae5c9.png)

So this change must be reverted....

We have the same problem with our React app. We have been using axios since 0.19 and 1.1.3 breaks our webpack build. Reverting to 1.1.2 fixes the problem for
now but this needs to be fixed.
ok, thank you!
i have same issue, can someone tell how to fix that with 1.1.3 (without downgrade to 1.1.2)?
yes, we need an actual fix for this, not to just revert to 1.1.2 in our code.
Given this issue isn't really fixed and instead only has a downgrade as workaround, we should probably keep this ticket open?
It works well with 1.2.0 version, but is broken again in 1.2.2
@KubaLorenc does it break in the same way as before the fix? If not, can you describe the failure mode?


I have the same problem when used in a library I am developing and after importing and using it in a CRA app. Its displays pollyfill errors (stream, https, zlib etc), I am using 1.3.5 v of axios. Is there any solution for this?
Can you share the errors? Did you try adding the polyfill it is complaining about, as a package dependency?
@ajmas Yes I added all the complaining polyfills, some errors were resolved but still there are more errors displaying as below. When I remove any use of axios in my library and imported the updated version to the sample app then the pollyfill errors are gone. Therefore I identified these polyfill errors come due to use of Axios (1.3.5)

```
If you want to include a polyfill, you need to:
	- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
	- install 'stream-browserify'
```
	
The above same error is displaying for stream-http, https-browserify, fs, tty-browserify, os-browserify, browserify-zlib. 


@mevannir  Are you able to create a sample project that demonstrates this issue? It would make it easier to analyse what is going on and seeing if there is a workaround too.

Running into this behavior as well after upgrading to 1.1.3.
Me too had to Go back to v **1.1.0** 
did lots of swears as well
Ran into this error also but all i just did was to set the error to the universal type "any" and that fix it for me.



Patch:
diff --git a/.gitignore b/.gitignore
index ca56b6361a..68af93b92e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,3 +7,6 @@ typings/
 coverage/
 test/typescript/axios.js*
 sauce_connect.log
+test/module/cjs/node_modules/
+test/module/cjs/package-lock.json
+backup/
diff --git a/.npmignore b/.npmignore
index 09739a34f8..f94390d8c9 100644
--- a/.npmignore
+++ b/.npmignore
@@ -16,3 +16,4 @@ Gruntfile.js
 karma.conf.js
 webpack.*.js
 sauce_connect.log
+backup/
diff --git a/README.md b/README.md
index b7260413fc..dde09743ba 100644
--- a/README.md
+++ b/README.md
@@ -35,6 +35,8 @@
   - [Features](#features)
   - [Browser Support](#browser-support)
   - [Installing](#installing)
+    - [Package manager](#package-manager)
+    - [CDN](#cdn)
   - [Example](#example)
   - [Axios API](#axios-api)
   - [Request method aliases](#request-method-aliases)
@@ -93,6 +95,8 @@ Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ |
 
 ## Installing
 
+### Package manager
+
 Using npm:
 
 ```bash
@@ -117,7 +121,39 @@ Using pnpm:
 $ pnpm add axios
 ```
 
-Using jsDelivr CDN:
+Once the package is installed, you can import the library using `import` or `require` approach:
+
+```js
+import axios, {isCancel, AxiosError} from 'axios';
+```
+
+You can also use the default export, since the named export is just a re-export from the Axios factory:
+
+```js
+import axios from 'axios';
+
+console.log(axios.isCancel('something'));
+````
+
+If you use `require` for importing, **only default export is available**:
+
+```js
+const axios = require('axios');
+
+console.log(axios.isCancel('something'));
+```
+
+For cases where something went wrong when trying to import a module into a custom or legacy environment,
+you can try importing the module package directly:
+
+```js
+const axios = require('axios/dist/browser/axios.cjs'); // browser commonJS bundle (ES2017)
+// const axios = require('axios/dist/node/axios.cjs'); // node commonJS bundle (ES2017)
+```
+
+### CDN
+
+Using jsDelivr CDN (ES5 UMD browser module):
 
 ```html
 <script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>
@@ -131,19 +167,11 @@ Using unpkg CDN:
 
 ## Example
 
-### note: CommonJS usage
-In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach:
-
-```js
-const axios = require('axios').default;
-
-// axios.<method> will now provide autocomplete and parameter typings
-```
-
 Performing a `GET` request
 
 ```js
-const axios = require('axios').default;
+import axios from 'axios';
+//const axios = require('axios'); // legacy way
 
 // Make a request for a user with a given ID
 axios.get('/user?ID=12345')
diff --git a/index.d.ts b/index.d.ts
index abc4d93aee..ecd5c85247 100644
--- a/index.d.ts
+++ b/index.d.ts
@@ -463,6 +463,18 @@ export interface GenericHTMLFormElement {
   submit(): void;
 }
 
+export function toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;
+
+export function formToJSON(form: GenericFormData|GenericHTMLFormElement): object;
+
+export function isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;
+
+export function spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
+
+export function isCancel(value: any): value is Cancel;
+
+export function all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
+
 export interface AxiosStatic extends AxiosInstance {
   create(config?: CreateAxiosDefaults): AxiosInstance;
   Cancel: CancelStatic;
@@ -470,12 +482,14 @@ export interface AxiosStatic extends AxiosInstance {
   Axios: typeof Axios;
   AxiosError: typeof AxiosError;
   readonly VERSION: string;
-  isCancel(value: any): value is Cancel;
-  all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
-  spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
-  isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;
-  toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;
-  formToJSON(form: GenericFormData|GenericHTMLFormElement): object;
+  isCancel: typeof isCancel;
+  all: typeof all;
+  spread: typeof spread;
+  isAxiosError: typeof isAxiosError;
+  toFormData: typeof toFormData;
+  formToJSON: typeof formToJSON;
+  CanceledError: typeof CanceledError;
+  AxiosHeaders: typeof AxiosHeaders;
 }
 
 declare const axios: AxiosStatic;
diff --git a/index.js b/index.js
index b5369d7842..f91032c024 100644
--- a/index.js
+++ b/index.js
@@ -1,5 +1,6 @@
 import axios from './lib/axios.js';
 
+// This module is intended to unwrap Axios default export as named.
 // Keep top-level export same with static properties
 // so that it can keep same with es module or cjs
 const {
@@ -13,11 +14,13 @@ const {
   Cancel,
   isAxiosError,
   spread,
-  toFormData
+  toFormData,
+  AxiosHeaders,
+  formToJSON
 } = axios;
 
-export default axios;
 export {
+  axios as default,
   Axios,
   AxiosError,
   CanceledError,
@@ -28,5 +31,7 @@ export {
   Cancel,
   isAxiosError,
   spread,
-  toFormData
+  toFormData,
+  AxiosHeaders,
+  formToJSON
 }
diff --git a/lib/axios.js b/lib/axios.js
index e79082ceb3..31b75b162b 100644
--- a/lib/axios.js
+++ b/lib/axios.js
@@ -14,6 +14,7 @@ import toFormData from './helpers/toFormData.js';
 import AxiosError from './core/AxiosError.js';
 import spread from './helpers/spread.js';
 import isAxiosError from './helpers/isAxiosError.js';
+import AxiosHeaders from "./core/AxiosHeaders.js";
 
 /**
  * Create an instance of Axios
@@ -69,8 +70,9 @@ axios.spread = spread;
 // Expose isAxiosError
 axios.isAxiosError = isAxiosError;
 
-axios.formToJSON = thing => {
-  return formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
-};
+axios.AxiosHeaders = AxiosHeaders;
+
+axios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
 
+// this module should only have a default export
 export default axios
diff --git a/package.json b/package.json
index 685f3fc86f..61e7b688ed 100644
--- a/package.json
+++ b/package.json
@@ -6,22 +6,24 @@
   "exports": {
     ".": {
       "browser": {
-        "require": "./dist/node/axios.cjs",
+        "require": "./dist/browser/axios.cjs",
         "default": "./index.js"
       },
       "default": {
         "require": "./dist/node/axios.cjs",
         "default": "./index.js"
       }
-    }
+    },
+    "./package.json": "./package.json"
   },
   "type": "module",
   "types": "index.d.ts",
   "scripts": {
-    "test": "npm run test:eslint && npm run test:mocha && npm run test:karma && npm run test:dtslint",
+    "test": "npm run test:eslint && npm run test:mocha && npm run test:karma && npm run test:exports && npm run test:dtslint",
     "test:eslint": "node bin/ssl_hotfix.js eslint lib/**/*.js",
     "test:dtslint": "node bin/ssl_hotfix.js dtslint",
     "test:mocha": "node bin/ssl_hotfix.js mocha test/unit/**/*.js --timeout 30000 --exit",
+    "test:exports": "node bin/ssl_hotfix.js mocha test/module/test.js --timeout 30000 --exit",
     "test:karma": "node bin/ssl_hotfix.js cross-env LISTEN_ADDR=:: karma start karma.conf.cjs --single-run",
     "test:karma:server": "node bin/ssl_hotfix.js cross-env karma start karma.conf.cjs",
     "start": "node ./sandbox/server.js",
@@ -131,4 +133,4 @@
     "Ben Carp (https://github.com/carpben)",
     "Daniel Lopretto (https://github.com/timemachine3030)"
   ]
-}
\ No newline at end of file
+}
diff --git a/rollup.config.js b/rollup.config.js
index 9fd12d1bac..31cc7bebce 100644
--- a/rollup.config.js
+++ b/rollup.config.js
@@ -5,20 +5,28 @@ import json from '@rollup/plugin-json';
 import { babel } from '@rollup/plugin-babel';
 import autoExternal from 'rollup-plugin-auto-external';
 import bundleSize from 'rollup-plugin-bundle-size'
+import path from 'path';
 
 const lib = require("./package.json");
 const outputFileName = 'axios';
 const name = "axios";
-const input = './lib/axios.js';
+const namedInput = './index.js';
+const defaultInput = './lib/axios.js';
 
 const buildConfig = ({es5, browser = true, minifiedVersion = true, ...config}) => {
+  const {file} = config.output;
+  const ext = path.extname(file);
+  const basename = path.basename(file, ext);
+  const extArr = ext.split('.');
+  extArr.shift();
+
 
   const build = ({minified}) => ({
-    input,
+    input: namedInput,
     ...config,
     output: {
       ...config.output,
-      file: `${config.output.file}.${minified ? "min.js" : "js"}`
+      file: `${path.dirname(file)}/${basename}.${(minified ? ['min', ...extArr] : extArr).join('.')}`
     },
     plugins: [
       json(),
@@ -50,10 +58,24 @@ export default async () => {
   const banner = `// Axios v${lib.version} Copyright (c) ${year} ${lib.author} and contributors`;
 
   return [
+    // browser ESM bundle for CDN
     ...buildConfig({
+      input: namedInput,
+      output: {
+        file: `dist/esm/${outputFileName}.js`,
+        format: "esm",
+        preferConst: true,
+        exports: "named",
+        banner
+      }
+    }),
+
+    // Browser UMD bundle for CDN
+    ...buildConfig({
+      input: defaultInput,
       es5: true,
       output: {
-        file: `dist/${outputFileName}`,
+        file: `dist/${outputFileName}.js`,
         name,
         format: "umd",
         exports: "default",
@@ -61,18 +83,23 @@ export default async () => {
       }
     }),
 
+    // Browser CJS bundle
     ...buildConfig({
+      input: defaultInput,
+      es5: false,
+      minifiedVersion: false,
       output: {
-        file: `dist/esm/${outputFileName}`,
-        format: "esm",
-        preferConst: true,
-        exports: "named",
+        file: `dist/browser/${name}.cjs`,
+        name,
+        format: "cjs",
+        exports: "default",
         banner
       }
     }),
-    // Node.js commonjs build
+
+    // Node.js commonjs bundle
     {
-      input,
+      input: defaultInput,
       output: {
         file: `dist/node/${name}.cjs`,
         format: "cjs",
diff --git a/tslint.json b/tslint.json
index 3ec44a760a..685d309ab5 100644
--- a/tslint.json
+++ b/tslint.json
@@ -1,6 +1,11 @@
-{ 
+{
   "extends": "dtslint/dtslint.json",
   "rules": {
     "no-unnecessary-generics": false
+  },
+  "linterOptions": {
+    "exclude": [
+      "test/module/**"
+    ]
   }
 }


Test patch:
diff --git a/test/module/cjs/index.js b/test/module/cjs/index.js
new file mode 100644
index 0000000000..7eb5dc034e
--- /dev/null
+++ b/test/module/cjs/index.js
@@ -0,0 +1,11 @@
+const axios = require('axios');
+const assert = require('assert');
+
+const {CanceledError, AxiosError, AxiosHeaders} = axios;
+
+assert.strictEqual(typeof axios, 'function');
+assert.strictEqual(typeof CanceledError, 'function');
+assert.strictEqual(typeof AxiosError, 'function');
+assert.strictEqual(typeof AxiosHeaders, 'function');
+
+console.log('CommonJS importing test passed');
diff --git a/test/module/cjs/package.json b/test/module/cjs/package.json
new file mode 100644
index 0000000000..1b198f46f7
--- /dev/null
+++ b/test/module/cjs/package.json
@@ -0,0 +1,15 @@
+{
+  "name": "cjs-entrypoint-test",
+  "version": "1.0.0",
+  "description": "",
+  "main": "index.js",
+  "scripts": {
+    "test": "npm i --no-save --no-package-lock && node index.js"
+  },
+  "keywords": [],
+  "author": "",
+  "license": "MIT",
+  "dependencies": {
+    "axios": "file:../../.."
+  }
+}
diff --git a/test/module/esm/index.js b/test/module/esm/index.js
new file mode 100644
index 0000000000..89d85bc1c6
--- /dev/null
+++ b/test/module/esm/index.js
@@ -0,0 +1,13 @@
+import assert from 'assert';
+import axios, {CanceledError, AxiosError, AxiosHeaders} from 'axios';
+
+assert.strictEqual(typeof axios, 'function');
+assert.strictEqual(typeof CanceledError, 'function');
+assert.strictEqual(typeof AxiosError, 'function');
+assert.strictEqual(typeof AxiosHeaders, 'function');
+
+assert.strictEqual(axios.CanceledError, CanceledError);
+assert.strictEqual(axios.AxiosError, AxiosError);
+assert.strictEqual(axios.AxiosHeaders, AxiosHeaders);
+
+console.log('ESM importing test passed');
diff --git a/test/module/esm/package.json b/test/module/esm/package.json
new file mode 100644
index 0000000000..162715065a
--- /dev/null
+++ b/test/module/esm/package.json
@@ -0,0 +1,16 @@
+{
+  "name": "esm-entrypoint-test",
+  "version": "1.0.0",
+  "description": "",
+  "main": "index.js",
+  "type": "module",
+  "scripts": {
+    "test": "npm i --no-save --no-package-lock && node index.js"
+  },
+  "keywords": [],
+  "author": "",
+  "license": "MIT",
+  "dependencies": {
+    "axios": "file:../../.."
+  }
+}
diff --git a/test/module/test.js b/test/module/test.js
new file mode 100644
index 0000000000..59c2ff8d8d
--- /dev/null
+++ b/test/module/test.js
@@ -0,0 +1,106 @@
+import assert from 'assert';
+import * as axios from '../../index.js';
+import axiosFactory from '../../lib/axios.js';
+import utils from "../../lib/utils.js";
+import {fileURLToPath} from 'url';
+import path from 'path';
+import util from "util";
+import cp from "child_process";
+import fs from 'fs-extra';
+
+const BACKUP_PATH = './backup/';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
+const exec = util.promisify(cp.exec);
+
+const {Axios} = axiosFactory;
+const ignoreList = [];
+
+const instance = axiosFactory.create({});
+
+const remove = async (file) => {
+  console.log(`✓ Remove entry '${file}'...`);
+  try {
+    await fs.remove(file);
+  } catch (err) {
+    console.warn(err);
+  }
+}
+
+describe('module', function () {
+
+  before(async ()=> {
+    console.log('✓ Creating build backup...');
+    await fs.copy('./dist/', BACKUP_PATH);
+    console.log('✓ Exec build script...');
+    await exec('npm run build');
+    console.log('✓ Running tests...');
+  });
+
+  after(async () => {
+    console.log('✓ Restore build from the backup...');
+    await fs.copy(BACKUP_PATH, './dist/');
+    await remove(BACKUP_PATH);
+  });
+
+  it('should have consistent ESM export', function () {
+    const namedExport = {};
+    const factoryExport = {};
+
+    Object.entries(axiosFactory).forEach(([key, value]) => {
+      if(!utils.hasOwnProp(Axios, key) && !(key in instance) && ignoreList.indexOf(key) === -1) {
+        factoryExport[key] = value;
+      }
+    });
+
+    Object.entries(axios).forEach(([key, value]) => {
+      key!=='default' && ignoreList.indexOf(key) === -1 && (namedExport[key] = value);
+    });
+
+    assert.deepStrictEqual(namedExport, factoryExport);
+  });
+
+  describe('CommonJS', ()=> {
+    const pkgPath = path.join(__dirname, './cjs');
+
+    after(async ()=> {
+      await remove(path.join(pkgPath, './node_modules'));
+    });
+
+    it('should be able to be loaded with require', async function () {
+      this.timeout(30000);
+
+      await exec(`npm test --prefix ${pkgPath}`);
+    });
+  });
+
+  describe('ESM', ()=> {
+    const pkgPath = path.join(__dirname, './esm');
+
+    after(async ()=> {
+      await remove(path.join(pkgPath, './node_modules'));
+    });
+
+    it('should be able to be loaded with import', async function () {
+      this.timeout(30000);
+
+      await exec(`npm test --prefix ${pkgPath}`);
+    });
+  });
+
+  describe('TS', ()=> {
+    const pkgPath = path.join(__dirname, './ts');
+
+    after(async ()=> {
+      await remove(path.join(pkgPath, './node_modules'));
+    });
+
+    it('should be able to be loaded with import', async function () {
+      this.timeout(30000);
+
+      await exec(`npm test --prefix ${pkgPath}`, {});
+    });
+  });
+
+});
diff --git a/test/module/ts/index.ts b/test/module/ts/index.ts
new file mode 100644
index 0000000000..ce88fb5e6c
--- /dev/null
+++ b/test/module/ts/index.ts
@@ -0,0 +1,24 @@
+import assert from 'assert';
+import axios, {CanceledError, AxiosError, AxiosHeaders, formToJSON, spread, isAxiosError, isCancel, all, toFormData} from 'axios';
+
+assert.strictEqual(typeof axios, 'function');
+
+assert.strictEqual(typeof CanceledError, 'function');
+assert.strictEqual(typeof AxiosError, 'function');
+assert.strictEqual(typeof AxiosHeaders, 'function');
+assert.strictEqual(typeof formToJSON, 'function');
+assert.strictEqual(typeof spread, 'function');
+assert.strictEqual(typeof isAxiosError, 'function');
+assert.strictEqual(typeof isCancel, 'function');
+assert.strictEqual(typeof all, 'function');
+assert.strictEqual(typeof toFormData, 'function');
+
+assert.strictEqual(typeof axios.CanceledError, 'function');
+assert.strictEqual(typeof axios.AxiosError, 'function');
+assert.strictEqual(typeof axios.AxiosHeaders, 'function');
+assert.strictEqual(typeof axios.formToJSON, 'function');
+assert.strictEqual(typeof axios.spread, 'function');
+assert.strictEqual(typeof axios.isAxiosError, 'function');
+assert.strictEqual(typeof axios.isCancel, 'function');
+assert.strictEqual(typeof axios.all, 'function');
+assert.strictEqual(typeof axios.toFormData, 'function');
diff --git a/test/module/ts/package.json b/test/module/ts/package.json
new file mode 100644
index 0000000000..23c39f3d46
--- /dev/null
+++ b/test/module/ts/package.json
@@ -0,0 +1,20 @@
+{
+  "name": "ts-entrypoint-test",
+  "version": "1.0.0",
+  "description": "",
+  "main": "index.js",
+  "scripts": {
+    "test": "npm i --no-save --no-package-lock && npm run build && node index.js",
+    "build": "tsc"
+  },
+  "keywords": [],
+  "author": "",
+  "license": "MIT",
+  "dependencies": {
+    "@types/node": "^18.11.3",
+    "axios": "file:../../.."
+  },
+  "devDependencies": {
+    "typescript": "^4.8.4"
+  }
+}
diff --git a/test/module/ts/tsconfig.json b/test/module/ts/tsconfig.json
new file mode 100644
index 0000000000..ac1c5dbca9
--- /dev/null
+++ b/test/module/ts/tsconfig.json
@@ -0,0 +1,103 @@
+{
+  "compilerOptions": {
+    /* Visit https://aka.ms/tsconfig to read more about this file */
+
+    /* Projects */
+    // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
+    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
+    // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
+    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
+    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
+    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */
+
+    /* Language and Environment */
+    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
+    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
+    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
+    // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
+    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
+    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
+    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
+    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
+    // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
+    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
+    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
+    // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */
+
+    /* Modules */
+    "module": "commonjs",                                /* Specify what module code is generated. */
+    // "rootDir": "./",                                  /* Specify the root folder within your source files. */
+     "moduleResolution": "node",                         /* Specify how TypeScript looks up a file from a given module specifier. */
+    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
+    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
+    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
+    // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
+    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
+    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
+    // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
+    // "resolveJsonModule": true,                        /* Enable importing .json files. */
+    // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
+
+    /* JavaScript Support */
+    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
+    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
+    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
+
+    /* Emit */
+    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
+    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
+    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
+    // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
+    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
+    // "outDir": "./",                                   /* Specify an output folder for all emitted files. */
+    // "removeComments": true,                           /* Disable emitting comments. */
+    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
+    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
+    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
+    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
+    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
+    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
+    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
+    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
+    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
+    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
+    // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
+    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
+    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
+    // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
+    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
+    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
+
+    /* Interop Constraints */
+    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
+    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
+    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
+    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
+    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
+
+    /* Type Checking */
+    "strict": true,                                      /* Enable all strict type-checking options. */
+    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
+    // "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
+    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
+    // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
+    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
+    // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
+    // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
+    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
+    // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
+    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
+    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
+    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
+    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
+    // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
+    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
+    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
+    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
+    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */
+
+    /* Completeness */
+    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
+    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
+  }
+}
diff --git a/test/specs/instance.spec.js b/test/specs/instance.spec.js
index 594a371eba..9306e344e5 100644
--- a/test/specs/instance.spec.js
+++ b/test/specs/instance.spec.js
@@ -26,7 +26,8 @@ describe('instance', function () {
         'VERSION',
         'default',
         'toFormData',
-        'formToJSON'
+        'formToJSON',
+        'AxiosHeaders'
       ].indexOf(prop) > -1) {
         continue;
       }
diff --git a/test/typescript/axios.ts b/test/typescript/axios.ts
index 617993eb43..01d32915f8 100644
--- a/test/typescript/axios.ts
+++ b/test/typescript/axios.ts
@@ -6,7 +6,13 @@ import axios, {
   AxiosAdapter,
   Cancel,
   CancelTokenSource,
-  Canceler, AxiosProgressEvent, ParamsSerializerOptions
+  Canceler, AxiosProgressEvent, ParamsSerializerOptions,
+  toFormData,
+  formToJSON,
+  all,
+  isCancel,
+  isAxiosError,
+  spread
 } from 'axios';
 
 const config: AxiosRequestConfig = {
@@ -354,11 +360,28 @@ const promises = [
 
 const promise: Promise<number[]> = axios.all(promises);
 
+// axios.all named export
+
+(() => {
+  const promises = [
+    Promise.resolve(1),
+    Promise.resolve(2)
+  ];
+
+  const promise: Promise<number[]> = all(promises);
+})();
+
 // axios.spread
 
 const fn1 = (a: number, b: number, c: number) => `${a}-${b}-${c}`;
 const fn2: (arr: number[]) => string = axios.spread(fn1);
 
+// axios.spread named export
+(() => {
+  const fn1 = (a: number, b: number, c: number) => `${a}-${b}-${c}`;
+  const fn2: (arr: number[]) => string = spread(fn1);
+})();
+
 // Promises
 
 axios.get('/user')
@@ -396,6 +419,12 @@ axios.get('/user', {
     const cancel: Cancel = thrown;
     console.log(cancel.message);
   }
+
+  // named export
+  if (isCancel(thrown)) {
+    const cancel: Cancel = thrown;
+    console.log(cancel.message);
+  }
 });
 
 source.cancel('Operation has been canceled.');
@@ -407,12 +436,28 @@ axios.get('/user')
     if (axios.isAxiosError(error)) {
       const axiosError: AxiosError = error;
     }
+
+    // named export
+
+    if (isAxiosError(error)) {
+      const axiosError: AxiosError = error;
+    }
   });
 
 // FormData
 
 axios.toFormData({x: 1}, new FormData());
 
+// named export
+toFormData({x: 1}, new FormData());
+
+// formToJSON
+
+axios.toFormData(new FormData());
+
+// named export
+formToJSON(new FormData());
+
 // AbortSignal
 
 axios.get('/user', {signal: new AbortController().signal});