Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored module exports; #5162

Merged
merged 5 commits into from Oct 30, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Expand Up @@ -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/
1 change: 1 addition & 0 deletions .npmignore
Expand Up @@ -16,3 +16,4 @@ Gruntfile.js
karma.conf.js
webpack.*.js
sauce_connect.log
backup/
24 changes: 18 additions & 6 deletions index.d.ts
Expand Up @@ -463,19 +463,31 @@ 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;
CancelToken: CancelTokenStatic;
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;
}

declare const axios: AxiosStatic;
Expand Down
11 changes: 8 additions & 3 deletions 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 {
Expand All @@ -13,11 +14,13 @@ const {
Cancel,
isAxiosError,
spread,
toFormData
toFormData,
AxiosHeaders,
formToJSON
} = axios;

export default axios;
export {
axios as default,
Axios,
AxiosError,
CanceledError,
Expand All @@ -28,5 +31,7 @@ export {
Cancel,
isAxiosError,
spread,
toFormData
toFormData,
AxiosHeaders,
formToJSON
}
8 changes: 5 additions & 3 deletions lib/axios.js
Expand Up @@ -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
Expand Down Expand Up @@ -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
10 changes: 6 additions & 4 deletions package.json
Expand Up @@ -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",
Expand Down Expand Up @@ -131,4 +133,4 @@
"Ben Carp (https://github.com/carpben)",
"Daniel Lopretto (https://github.com/timemachine3030)"
]
}
}
47 changes: 37 additions & 10 deletions rollup.config.js
Expand Up @@ -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(),
Expand Down Expand Up @@ -50,29 +58,48 @@ 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",
banner
}
}),

// 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",
Expand Down
11 changes: 11 additions & 0 deletions 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');
15 changes: 15 additions & 0 deletions test/module/cjs/package.json
@@ -0,0 +1,15 @@
{
"name": "cjs-module-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:../../.."
}
}
74 changes: 74 additions & 0 deletions test/module/test.js
@@ -0,0 +1,74 @@
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 = (file) => {
console.log(`✓ Remove entry '${file}'...`);
return fs.remove(file);
}

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}`);
Fixed Show fixed Hide fixed

Check warning

Code scanning / CodeQL

Shell command built from environment values

This shell command depends on an uncontrolled [absolute path](1).
});
});

});
3 changes: 2 additions & 1 deletion test/specs/instance.spec.js
Expand Up @@ -26,7 +26,8 @@ describe('instance', function () {
'VERSION',
'default',
'toFormData',
'formToJSON'
'formToJSON',
'AxiosHeaders'
].indexOf(prop) > -1) {
continue;
}
Expand Down