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

在前端项目中用这个替换 axios 和 qs 模块并减少 73KB! #6266

Open
suhaotian opened this issue Mar 11, 2025 · 0 comments
Open

Comments

@suhaotian
Copy link

suhaotian commented Mar 11, 2025

在前端项目中替换 axiosqs 模块,减少 73KB!

之前使用 qs 的原因是:

  • 将嵌套对象编码为 URL 查询字符串:
    qs.stringify({ a: { b: 1 } })
  • 解析查询字符串为对象:
    qs.parse(location.search).token

然而,你可以使用更轻量的替代方案实现相同功能:

  • 解析查询字符串为对象,可以使用浏览器自带的 URLSearchParams
    new URLSearchParams(location.search).get('token')
  • 将嵌套对象编码为 URL 查询字符串,可以使用 xior 提供的轻量实现:
    import { encodeParams as stringify } from 'xior';  
    stringify({ a: { b: 1 } });

至于 axios,许多开发者使用它是因为它的便捷 API。然而,使用这个类似 axiosFetch 封装,你可以将包体积从 35.6KB 减少到 6KB

各模块的体积对比:

  • axios 模块大小:
axios size: 35.6KB -> 13.6KB(gzip)
  • qs 模块大小:
qs size: 38KB -> 11.4KB(gzip)

6.32KB -> 2.98KB(gzip)

而且 API 几乎与 Axios 相同:

唯一的区别就是 axios 换成 xior

import axios, {
  XiorError as AxiosError,
  isXiorError as isAxiosError,
  XiorRequestConfig as AxiosRequestConfig,
  XiorResponse as AxiosResponse,
} from 'xior';

const instance = axios.create({
  baseURL: '...',
  timeout: 20e3,
});

所以,为什么你还在前端项目中使用 qsaxios

如果有任何问题或遇到 bug,请留言或创建 Issue。

立即查看 👉 https://github.com/suhaotian/xior


原文翻译自:Replace axios and qs modules with this in frontend projects and reduce 73KB!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant