Skip to content

Commit 0c3a1e9

Browse files
authoredOct 30, 2022
Refactored module exports; (axios#5162)
* Refactored build pipeline; Added module exports tests; Added missing ESM export for parity with Axios factory; Added `toFormData`, `formToJSON`, `isAxiosError`, `spread`, `isCancel`, `all` as named export to `index.d.ts`; * Added ESM entry test; * Updated README.md `installing` section; * Added TypeScript importing test; Added missed `CanceledError` & `AxiosHeaders` to `AxiosStatic` interface; * Exclude `/test/module/` from tslint;
1 parent 5666ee4 commit 0c3a1e9

19 files changed

+481
-40
lines changed
 

‎.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,6 @@ typings/
77
coverage/
88
test/typescript/axios.js*
99
sauce_connect.log
10+
test/module/cjs/node_modules/
11+
test/module/cjs/package-lock.json
12+
backup/

‎.npmignore

+1
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,4 @@ Gruntfile.js
1616
karma.conf.js
1717
webpack.*.js
1818
sauce_connect.log
19+
backup/

‎README.md

+39-11
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@
3535
- [Features](#features)
3636
- [Browser Support](#browser-support)
3737
- [Installing](#installing)
38+
- [Package manager](#package-manager)
39+
- [CDN](#cdn)
3840
- [Example](#example)
3941
- [Axios API](#axios-api)
4042
- [Request method aliases](#request-method-aliases)
@@ -93,6 +95,8 @@ Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ |
9395

9496
## Installing
9597

98+
### Package manager
99+
96100
Using npm:
97101

98102
```bash
@@ -117,7 +121,39 @@ Using pnpm:
117121
$ pnpm add axios
118122
```
119123

120-
Using jsDelivr CDN:
124+
Once the package is installed, you can import the library using `import` or `require` approach:
125+
126+
```js
127+
import axios, {isCancel, AxiosError} from 'axios';
128+
```
129+
130+
You can also use the default export, since the named export is just a re-export from the Axios factory:
131+
132+
```js
133+
import axios from 'axios';
134+
135+
console.log(axios.isCancel('something'));
136+
````
137+
138+
If you use `require` for importing, **only default export is available**:
139+
140+
```js
141+
const axios = require('axios');
142+
143+
console.log(axios.isCancel('something'));
144+
```
145+
146+
For cases where something went wrong when trying to import a module into a custom or legacy environment,
147+
you can try importing the module package directly:
148+
149+
```js
150+
const axios = require('axios/dist/browser/axios.cjs'); // browser commonJS bundle (ES2017)
151+
// const axios = require('axios/dist/node/axios.cjs'); // node commonJS bundle (ES2017)
152+
```
153+
154+
### CDN
155+
156+
Using jsDelivr CDN (ES5 UMD browser module):
121157

122158
```html
123159
<script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>
@@ -131,19 +167,11 @@ Using unpkg CDN:
131167

132168
## Example
133169

134-
### note: CommonJS usage
135-
In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach:
136-
137-
```js
138-
const axios = require('axios').default;
139-
140-
// axios.<method> will now provide autocomplete and parameter typings
141-
```
142-
143170
Performing a `GET` request
144171

145172
```js
146-
const axios = require('axios').default;
173+
import axios from 'axios';
174+
//const axios = require('axios'); // legacy way
147175
148176
// Make a request for a user with a given ID
149177
axios.get('/user?ID=12345')

‎index.d.ts

+20-6
Original file line numberDiff line numberDiff line change
@@ -463,19 +463,33 @@ export interface GenericHTMLFormElement {
463463
submit(): void;
464464
}
465465

466+
export function toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;
467+
468+
export function formToJSON(form: GenericFormData|GenericHTMLFormElement): object;
469+
470+
export function isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;
471+
472+
export function spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
473+
474+
export function isCancel(value: any): value is Cancel;
475+
476+
export function all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
477+
466478
export interface AxiosStatic extends AxiosInstance {
467479
create(config?: CreateAxiosDefaults): AxiosInstance;
468480
Cancel: CancelStatic;
469481
CancelToken: CancelTokenStatic;
470482
Axios: typeof Axios;
471483
AxiosError: typeof AxiosError;
472484
readonly VERSION: string;
473-
isCancel(value: any): value is Cancel;
474-
all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
475-
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
476-
isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;
477-
toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;
478-
formToJSON(form: GenericFormData|GenericHTMLFormElement): object;
485+
isCancel: typeof isCancel;
486+
all: typeof all;
487+
spread: typeof spread;
488+
isAxiosError: typeof isAxiosError;
489+
toFormData: typeof toFormData;
490+
formToJSON: typeof formToJSON;
491+
CanceledError: typeof CanceledError;
492+
AxiosHeaders: typeof AxiosHeaders;
479493
}
480494

481495
declare const axios: AxiosStatic;

‎index.js

+8-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import axios from './lib/axios.js';
22

3+
// This module is intended to unwrap Axios default export as named.
34
// Keep top-level export same with static properties
45
// so that it can keep same with es module or cjs
56
const {
@@ -13,11 +14,13 @@ const {
1314
Cancel,
1415
isAxiosError,
1516
spread,
16-
toFormData
17+
toFormData,
18+
AxiosHeaders,
19+
formToJSON
1720
} = axios;
1821

19-
export default axios;
2022
export {
23+
axios as default,
2124
Axios,
2225
AxiosError,
2326
CanceledError,
@@ -28,5 +31,7 @@ export {
2831
Cancel,
2932
isAxiosError,
3033
spread,
31-
toFormData
34+
toFormData,
35+
AxiosHeaders,
36+
formToJSON
3237
}

‎lib/axios.js

+5-3
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import toFormData from './helpers/toFormData.js';
1414
import AxiosError from './core/AxiosError.js';
1515
import spread from './helpers/spread.js';
1616
import isAxiosError from './helpers/isAxiosError.js';
17+
import AxiosHeaders from "./core/AxiosHeaders.js";
1718

1819
/**
1920
* Create an instance of Axios
@@ -69,8 +70,9 @@ axios.spread = spread;
6970
// Expose isAxiosError
7071
axios.isAxiosError = isAxiosError;
7172

72-
axios.formToJSON = thing => {
73-
return formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
74-
};
73+
axios.AxiosHeaders = AxiosHeaders;
74+
75+
axios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
7576

77+
// this module should only have a default export
7678
export default axios

‎package.json

+6-4
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,24 @@
66
"exports": {
77
".": {
88
"browser": {
9-
"require": "./dist/node/axios.cjs",
9+
"require": "./dist/browser/axios.cjs",
1010
"default": "./index.js"
1111
},
1212
"default": {
1313
"require": "./dist/node/axios.cjs",
1414
"default": "./index.js"
1515
}
16-
}
16+
},
17+
"./package.json": "./package.json"
1718
},
1819
"type": "module",
1920
"types": "index.d.ts",
2021
"scripts": {
21-
"test": "npm run test:eslint && npm run test:mocha && npm run test:karma && npm run test:dtslint",
22+
"test": "npm run test:eslint && npm run test:mocha && npm run test:karma && npm run test:exports && npm run test:dtslint",
2223
"test:eslint": "node bin/ssl_hotfix.js eslint lib/**/*.js",
2324
"test:dtslint": "node bin/ssl_hotfix.js dtslint",
2425
"test:mocha": "node bin/ssl_hotfix.js mocha test/unit/**/*.js --timeout 30000 --exit",
26+
"test:exports": "node bin/ssl_hotfix.js mocha test/module/test.js --timeout 30000 --exit",
2527
"test:karma": "node bin/ssl_hotfix.js cross-env LISTEN_ADDR=:: karma start karma.conf.cjs --single-run",
2628
"test:karma:server": "node bin/ssl_hotfix.js cross-env karma start karma.conf.cjs",
2729
"start": "node ./sandbox/server.js",
@@ -131,4 +133,4 @@
131133
"Ben Carp (https://github.com/carpben)",
132134
"Daniel Lopretto (https://github.com/timemachine3030)"
133135
]
134-
}
136+
}

‎rollup.config.js

+37-10
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,28 @@ import json from '@rollup/plugin-json';
55
import { babel } from '@rollup/plugin-babel';
66
import autoExternal from 'rollup-plugin-auto-external';
77
import bundleSize from 'rollup-plugin-bundle-size'
8+
import path from 'path';
89

910
const lib = require("./package.json");
1011
const outputFileName = 'axios';
1112
const name = "axios";
12-
const input = './lib/axios.js';
13+
const namedInput = './index.js';
14+
const defaultInput = './lib/axios.js';
1315

1416
const buildConfig = ({es5, browser = true, minifiedVersion = true, ...config}) => {
17+
const {file} = config.output;
18+
const ext = path.extname(file);
19+
const basename = path.basename(file, ext);
20+
const extArr = ext.split('.');
21+
extArr.shift();
22+
1523

1624
const build = ({minified}) => ({
17-
input,
25+
input: namedInput,
1826
...config,
1927
output: {
2028
...config.output,
21-
file: `${config.output.file}.${minified ? "min.js" : "js"}`
29+
file: `${path.dirname(file)}/${basename}.${(minified ? ['min', ...extArr] : extArr).join('.')}`
2230
},
2331
plugins: [
2432
json(),
@@ -50,29 +58,48 @@ export default async () => {
5058
const banner = `// Axios v${lib.version} Copyright (c) ${year} ${lib.author} and contributors`;
5159

5260
return [
61+
// browser ESM bundle for CDN
5362
...buildConfig({
63+
input: namedInput,
64+
output: {
65+
file: `dist/esm/${outputFileName}.js`,
66+
format: "esm",
67+
preferConst: true,
68+
exports: "named",
69+
banner
70+
}
71+
}),
72+
73+
// Browser UMD bundle for CDN
74+
...buildConfig({
75+
input: defaultInput,
5476
es5: true,
5577
output: {
56-
file: `dist/${outputFileName}`,
78+
file: `dist/${outputFileName}.js`,
5779
name,
5880
format: "umd",
5981
exports: "default",
6082
banner
6183
}
6284
}),
6385

86+
// Browser CJS bundle
6487
...buildConfig({
88+
input: defaultInput,
89+
es5: false,
90+
minifiedVersion: false,
6591
output: {
66-
file: `dist/esm/${outputFileName}`,
67-
format: "esm",
68-
preferConst: true,
69-
exports: "named",
92+
file: `dist/browser/${name}.cjs`,
93+
name,
94+
format: "cjs",
95+
exports: "default",
7096
banner
7197
}
7298
}),
73-
// Node.js commonjs build
99+
100+
// Node.js commonjs bundle
74101
{
75-
input,
102+
input: defaultInput,
76103
output: {
77104
file: `dist/node/${name}.cjs`,
78105
format: "cjs",

‎test/module/cjs/index.js

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
const axios = require('axios');
2+
const assert = require('assert');
3+
4+
const {CanceledError, AxiosError, AxiosHeaders} = axios;
5+
6+
assert.strictEqual(typeof axios, 'function');
7+
assert.strictEqual(typeof CanceledError, 'function');
8+
assert.strictEqual(typeof AxiosError, 'function');
9+
assert.strictEqual(typeof AxiosHeaders, 'function');
10+
11+
console.log('CommonJS importing test passed');

‎test/module/cjs/package.json

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"name": "cjs-entrypoint-test",
3+
"version": "1.0.0",
4+
"description": "",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "npm i --no-save --no-package-lock && node index.js"
8+
},
9+
"keywords": [],
10+
"author": "",
11+
"license": "MIT",
12+
"dependencies": {
13+
"axios": "file:../../.."
14+
}
15+
}

‎test/module/esm/index.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import assert from 'assert';
2+
import axios, {CanceledError, AxiosError, AxiosHeaders} from 'axios';
3+
4+
assert.strictEqual(typeof axios, 'function');
5+
assert.strictEqual(typeof CanceledError, 'function');
6+
assert.strictEqual(typeof AxiosError, 'function');
7+
assert.strictEqual(typeof AxiosHeaders, 'function');
8+
9+
assert.strictEqual(axios.CanceledError, CanceledError);
10+
assert.strictEqual(axios.AxiosError, AxiosError);
11+
assert.strictEqual(axios.AxiosHeaders, AxiosHeaders);
12+
13+
console.log('ESM importing test passed');

‎test/module/esm/package.json

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"name": "esm-entrypoint-test",
3+
"version": "1.0.0",
4+
"description": "",
5+
"main": "index.js",
6+
"type": "module",
7+
"scripts": {
8+
"test": "npm i --no-save --no-package-lock && node index.js"
9+
},
10+
"keywords": [],
11+
"author": "",
12+
"license": "MIT",
13+
"dependencies": {
14+
"axios": "file:../../.."
15+
}
16+
}

0 commit comments

Comments
 (0)
Please sign in to comment.