2026前端开发效率革命:15个必备工具库完全指南
一、通用工具库:提升开发效率的基石
1. Lodash - JavaScript实用工具库之王
GitHub: lodash/lodash ⭐ 59.3k+
npm周下载量: 4800万+
包大小: ~70KB (完整包), 支持按需引入
核心特性
Lodash是一个一致性、模块化、高性能的JavaScript实用工具库,提供数组、对象、字符串、函数等操作的便捷方法。
- 数据处理: 深拷贝、去重、分组、排序
- 函数工具: 防抖(debounce)、节流(throttle)、柯里化(curry)
- 类型检查: 比原生typeof更准确的类型判断
- 路径访问: 安全访问嵌套对象属性
安装使用
npm install lodash
优秀示例
import _ from 'lodash';
// 1. 深拷贝(避免引用污染)
const original = {
user: {
name: '张三',
hobbies: ['阅读', '编程']
}
};
const copy = _.cloneDeep(original);
copy.user.hobbies.push('运动');
console.log(original.user.hobbies); // ['阅读', '编程'] - 不受影响
// 2. 防抖优化搜索(500ms延迟执行)
const searchInput = document.querySelector('#search');
const handleSearch = _.debounce((keyword) => {
console.log('搜索:', keyword);
// 调用API...
}, 500);
searchInput.addEventListener('input', (e) => handleSearch(e.target.value));
// 3. 安全获取嵌套属性(避免报错)
const user = {
profile: {
address: { city: '北京' }
}
};
_.get(user, 'profile.address.city', '未知'); // "北京"
_.get(user, 'profile.phone', '未填写'); // "未填写"
// 4. 数组智能分组
const orders = [
{ id: 1, status: 'pending', amount: 100 },
{ id: 2, status: 'completed', amount: 200 },
{ id: 3, status: 'pending', amount: 150 }
];
const grouped = _.groupBy(orders, 'status');
// { pending: [...], completed: [...] }
// 5. 按需引入(减小打包体积)
import debounce from 'lodash/debounce';
import cloneDeep from 'lodash/cloneDeep';
适用场景
- 复杂数据处理和转换
- 需要防抖/节流的交互场景
- 深度对象操作
- 大型项目的工具函数统一
2. Day.js - 轻量级日期处理专家
GitHub: iamkun/dayjs ⭐ 45.2k+
npm周下载量: 1500万+
包大小: 仅2KB (压缩后)
核心特性
Day.js是Moment.js的现代替代品,保持相同API设计但体积极小,是不可变的日期处理库。
- 极小体积: 仅2KB,不增加项目负担
- 不可变设计: 所有操作返回新实例,避免副作用
- 插件系统: 按需加载时区、相对时间等功能
- 多语言支持: 内置100+语言包
安装使用
npm install dayjs
优秀示例
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/zh-cn';
// 启用插件
dayjs.extend(relativeTime);
dayjs.locale('zh-cn');
// 1. 基础格式化
console.log(dayjs().format('YYYY-MM-DD HH:mm:ss'));
// "2026-04-22 14:30:00"
console.log(dayjs().format('dddd, MMMM D, YYYY'));
// "星期三, 四月 22, 2026"
// 2. 日期计算
const tomorrow = dayjs().add(1, 'day');
const lastWeek = dayjs().subtract(7, 'days');
const nextMonth = dayjs().add(1, 'month').startOf('month');
// 3. 日期比较
const date1 = dayjs('2024-01-01');
const date2 = dayjs('2024-02-01');
console.log(date2.diff(date1, 'days')); // 31
console.log(date1.isBefore(date2)); // true
// 4. 相对时间(人性化显示)
console.log(dayjs('2026-04-20').fromNow()); // "2天前"
console.log(dayjs('2026-04-25').fromNow()); // "3天后"
// 5. 日期范围生成
const start = dayjs('2026-04-01');
const end = dayjs('2026-04-07');
const dates = [];
let current = start;
while (current.isBefore(end) || current.isSame(end, 'day')) {
dates.push(current.format('YYYY-MM-DD'));
current = current.add(1, 'day');
}
console.log(dates);
// ['2026-04-01', '2026-04-02', ..., '2026-04-07']
// 6. 解析多种格式
dayjs('2026-04-22');
dayjs('04/22/2026', 'MM/DD/YYYY');
dayjs(1713772200000); // 时间戳
替代方案对比
| 库名 | 体积 | 特点 | 推荐场景 |
|---|---|---|---|
| Day.js | 2KB | 轻量、API兼容Moment | 现代项目首选 |
| date-fns | ~8KB | 函数式、Tree-shakable | 需要按需引入 |
| Luxon | ~65KB | Moment官方继任者 | 复杂时区需求 |
| Moment.js | ~300KB | 已停止维护 | ❌ 不推荐新项目使用 |
二、网络请求库:优雅处理HTTP通信
3. Axios - 最流行的HTTP客户端
GitHub: axios/axios ⭐ 104k+
npm周下载量: 4500万+
包大小: ~13KB
核心特性
Axios是基于Promise的HTTP客户端,支持浏览器和Node.js环境。
- Promise支持: 完美配合async/await
- 拦截器: 请求/响应拦截,统一处理token、错误
- 自动转换: 自动序列化JSON数据
- 取消请求: 避免无效请求浪费资源
- 广泛兼容: 支持IE11+及所有现代浏览器
安装使用
npm install axios
实战封装示例
// utils/request.js - 统一请求封装
import axios from 'axios';
import { message } from 'antd';
// 创建实例
const service = axios.create({
baseURL: '/api',
timeout: 15000,
withCredentials: true // 携带cookie
});
// 请求拦截器:添加token
service.interceptors.request.use(
config => {
const token = localStorage.getItem('token');
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
},
error => Promise.reject(error)
);
// 响应拦截器:统一错误处理
service.interceptors.response.use(
response => {
const { code, data, msg } = response.data;
if (code === 200) {
return data;
} else if (code === 401) {
// 未登录,跳转登录页
window.location.href = `/login?redirect=${encodeURIComponent(window.location.href)}`;
return Promise.reject(new Error('未登录'));
} else {
message.error(msg || '请求失败');
return Promise.reject(new Error(msg));
}
},
error => {
console.error('请求错误:', error);
message.error(error.message || '网络异常');
return Promise.reject(error);
}
);
export default service;
接口模块化管理
// api/user.js - 用户相关接口
import request from '@/utils/request';
export const login = (data) => {
return request.post('/user/login', data);
};
export const getUserInfo = () => {
return request.get('/user/info');
};
export const updateUser = (data) => {
return request.put('/user/update', data);
};
业务中使用
// Login.vue
import { login } from '@/api/user';
import { ref } from 'vue';
const loading = ref(false);
const handleLogin = async (formData) => {
try {
loading.value = true;
const userInfo = await login(formData);
localStorage.setItem('token', userInfo.token);
console.log('登录成功', userInfo);
} catch (error) {
console.error('登录失败', error);
} finally {
loading.value = false;
}
};
新兴替代方案
| 库名 | GitHub Stars | 特点 | 适用场景 |
|---|---|---|---|
| Axios | 104k+ | 成熟稳定、生态完善 | 大多数项目 |
| ofetch | 3k+ | Nuxt官方推荐、自动重试 | Vue/Nuxt项目 |
| wretch | 4k+ | 链式调用、轻量 | 喜欢链式语法 |
| Redaxios | 1k+ | <1KB、API兼容Axios | 追求极致轻量 |
| alova | 6k+ | 内置缓存、请求去重 | 需要缓存策略 |
三、数据校验与安全:保障数据质量
4. Zod - TypeScript优先的数据验证库
GitHub: colinhacks/zod ⭐ 32k+
npm周下载量: 5100万+
包大小: ~10KB (gzip)
核心特性
Zod是TypeScript-first的schema声明和验证库,与TypeScript完美集成。
- 类型推导: Schema直接推导TypeScript类型
- 零依赖: 无第三方依赖,轻量高效
- 运行时验证: 编译时+运行时双重保障
- 丰富验证器: 字符串、数字、数组、对象等
安装使用
npm install zod
优秀示例
import { z } from 'zod';
// 1. 定义Schema并推导类型
const UserSchema = z.object({
username: z.string()
.min(3, '用户名至少3个字符')
.max(20, '用户名最多20个字符'),
email: z.string()
.email('邮箱格式不正确'),
age: z.number()
.int('年龄必须是整数')
.min(18, '必须年满18岁')
.max(120, '年龄不合理'),
password: z.string()
.min(8, '密码至少8位')
.regex(/[A-Z]/, '必须包含大写字母')
.regex(/[a-z]/, '必须包含小写字母')
.regex(/\d/, '必须包含数字')
});
// 自动推导TypeScript类型
type User = z.infer<typeof UserSchema>;
// 2. 数据验证
const result = UserSchema.safeParse({
username: 'john_doe',
email: 'john@example.com',
age: 25,
password: 'Password123'
});
if (result.success) {
console.log('验证通过', result.data);
} else {
console.error('验证失败', result.error.errors);
}
// 3. 表单验证集成(React Hook Form)
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
function UserForm() {
const { register, handleSubmit, formState: { errors } } = useForm<User>({
resolver: zodResolver(UserSchema)
});
const onSubmit = (data: User) => {
console.log('提交数据', data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span>{errors.username.message}</span>}
<input type="email" {...register('email')} />
{errors.email && <span>{errors.email.message}</span>}
<button type="submit">提交</button>
</form>
);
}
对比其他验证库
| 特性 | Zod | Yup | Joi |
|---|---|---|---|
| TypeScript支持 | ✅ 完美 | ⚠️ 需手动定义 | ❌ 不支持 |
| 同步验证 | ✅ | ❌ 仅异步 | ✅ |
| 包体积 | ~10KB | ~8KB | ~100KB |
| 类型推导 | ✅ 自动 | ❌ | ❌ |
| 适用场景 | TS项目首选 | 简单表单 | Node.js后端 |
5. XSS防护库
GitHub: leizongmin/js-xss ⭐ 13.5k+
npm周下载量: 200万+
核心特性
防止跨站脚本攻击(XSS),过滤HTML中的恶意代码。
- 白名单机制: 指定允许的标签和属性
- 自定义过滤: 灵活配置过滤规则
- 轻量多端: 浏览器和Node.js均可使用
安装使用
npm install xss
实战示例
import xss from 'xss';
// 1. 基础过滤(转义危险标签)
const userInput = '<script>alert("XSS")</script><p>安全文本</p>';
const safeOutput = xss(userInput);
// <script>alert("XSS")</script><p>安全文本</p>
// 2. 配置白名单
const options = {
whiteList: {
a: ['href', 'title'],
img: ['src', 'alt'],
p: [],
strong: []
},
// 自定义属性处理
onTagAttr: (tag, name, value) => {
if (tag === 'a' && name === 'href') {
// 只允许http/https链接
if (!/^https?:\/\//.test(value)) {
return `${name}="#"`;
}
}
}
};
const mixedInput = `
<script>alert("XSS")</script>
<a href="http://example.com">正常链接</a>
<a href="javascript:alert('攻击')">恶意链接</a>
<img src="image.jpg" alt="图片">
`;
const safeHtml = xss(mixedInput, options);
console.log(safeHtml);
// <p><script>alert("XSS")</script></p>
// <a href="http://example.com">正常链接</a>
// <a href="#">恶意链接</a>
// <img src="image.jpg" alt="图片">
四、文件处理工具:前端Excel/ZIP操作
6. SheetJS (xlsx) - Excel处理神器
GitHub: SheetJS/sheetjs ⭐ 37.5k+
npm周下载量: 800万+
核心特性
强大的Excel读写库,支持xls、xlsx、csv等多种格式。
- 导入导出: 读取和生成Excel文件
- 格式保留: 支持单元格样式、公式
- 大数据量: 高效处理大型表格
- 多格式支持: xls、xlsx、csv、ods等
安装使用
npm install xlsx
优秀示例
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
// 1. 导出数据到Excel
const exportToExcel = (data, filename = 'data.xlsx') => {
// 创建工作簿
const wb = XLSX.utils.book_new();
// 将数据转换为工作表
const ws = XLSX.utils.json_to_sheet(data);
// 设置列宽
ws['!cols'] = [
{ wch: 15 }, // 第一列宽度
{ wch: 20 }, // 第二列宽度
{ wch: 10 } // 第三列宽度
];
// 添加工作表到工作簿
XLSX.utils.book_append_sheet(wb, ws, '数据表');
// 生成Excel文件
const excelBuffer = XLSX.write(wb, {
bookType: 'xlsx',
type: 'array'
});
// 保存文件
const blob = new Blob([excelBuffer], {
type: 'application/octet-stream'
});
saveAs(blob, filename);
};
// 使用示例
const userData = [
{ 姓名: '张三', 年龄: 25, 城市: '北京' },
{ 姓名: '李四', 年龄: 30, 城市: '上海' },
{ 姓名: '王五', 年龄: 28, 城市: '广州' }
];
exportToExcel(userData, '用户列表.xlsx');
// 2. 读取Excel文件
const readExcel = (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array' });
// 获取第一个工作表
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
// 转换为JSON
const jsonData = XLSX.utils.sheet_to_json(worksheet);
resolve(jsonData);
};
reader.onerror = reject;
reader.readAsArrayBuffer(file);
});
};
// 3. 带样式的Excel导出(需要xlsx-style)
import XLSXStyle from 'xlsx-style';
const exportStyledExcel = (data) => {
const wb = XLSX.utils.book_new();
const ws = XLSX.utils.json_to_sheet(data);
// 设置表头样式
const range = XLSX.utils.decode_range(ws['!ref']);
for (let C = range.s.c; C <= range.e.c; ++C) {
const address = XLSX.utils.encode_col(C) + "1";
if (!ws[address]) continue;
ws[address].s = {
font: { bold: true, color: { rgb: "FFFFFF" } },
fill: { fgColor: { rgb: "4472C4" } },
alignment: { horizontal: "center" }
};
}
XLSX.utils.book_append_sheet(wb, ws, '数据');
XLSX.writeFile(wb, 'styled.xlsx');
};
7. JSZip - 前端ZIP压缩解压
GitHub: Stuk/jszip ⭐ 7.8k+
npm周下载量: 500万+
核心特性
纯前端ZIP文件创建、读取和编辑库。
- 纯前端实现: 无需后端参与
- 简单易用: 直观的API设计
- 流式处理: 支持大文件处理
安装使用
npm install jszip file-saver
批量下载并打包示例
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
import axios from 'axios';
// 批量下载图片并打包成ZIP
const downloadAndZip = async (files) => {
const zip = new JSZip();
const folder = zip.folder("下载的图片");
// 显示加载状态
console.log('开始下载...');
// 逐个下载文件
for (const file of files) {
try {
const response = await axios.get(file.url, {
responseType: 'blob'
});
// 添加到ZIP
folder.file(file.name, response.data);
console.log(`已添加: ${file.name}`);
} catch (error) {
console.error(`下载失败: ${file.name}`, error);
}
}
// 生成ZIP文件
console.log('正在压缩...');
const content = await zip.generateAsync({
type: 'blob',
compression: 'DEFLATE',
compressionOptions: { level: 6 }
});
// 保存文件
saveAs(content, '图片合集.zip');
console.log('下载完成!');
};
// 使用示例
const images = [
{ name: 'photo1.jpg', url: 'https://example.com/photo1.jpg' },
{ name: 'photo2.jpg', url: 'https://example.com/photo2.jpg' },
{ name: 'photo3.jpg', url: 'https://example.com/photo3.jpg' }
];
downloadAndZip(images);
8. FileSaver.js - 文件保存解决方案
GitHub: eligrey/FileSaver.js ⭐ 28.5k+
npm周下载量: 600万+
核心特性
解决浏览器文件下载的兼容性问题。
- 跨浏览器: 支持所有主流浏览器
- 简单易用: 一行代码保存文件
- Blob支持: 完美配合各种文件类型
安装使用
npm install file-saver
使用示例
import { saveAs } from 'file-saver';
// 1. 保存文本文件
const blob = new Blob(["Hello World"], {
type: "text/plain;charset=utf-8"
});
saveAs(blob, "hello.txt");
// 2. 保存JSON文件
const data = { name: '张三', age: 25 };
const jsonBlob = new Blob([JSON.stringify(data, null, 2)], {
type: "application/json"
});
saveAs(jsonBlob, "data.json");
// 3. 保存图片
const canvas = document.querySelector('canvas');
canvas.toBlob((blob) => {
saveAs(blob, 'screenshot.png');
});
// 4. 配合其他库使用
import * as XLSX from 'xlsx';
const wb = XLSX.utils.book_new();
const ws = XLSX.utils.json_to_sheet([{ name: '张三' }]);
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
const excelBlob = new Blob([excelBuffer], {
type: 'application/octet-stream'
});
saveAs(excelBlob, 'export.xlsx');
五、UI与样式工具:快速构建美观界面
9. Tailwind CSS - 原子化CSS框架
GitHub: tailwindlabs/tailwindcss ⭐ 82.5k+
npm周下载量: 900万+
核心特性
Utility-first的CSS框架,通过组合原子类快速构建界面。
- 高度定制: 配置文件定义设计系统
- 按需生成: 只打包使用的类,体积极小
- 响应式: 内置断点前缀(sm:、md:、lg:)
- 暗色模式: 原生支持dark:前缀
安装使用
npm install -D tailwindcss
npx tailwindcss init
优秀示例
<!-- 1. 基础卡片组件 -->
<div class="max-w-sm rounded-lg overflow-hidden shadow-lg bg-white">
<img class="w-full h-48 object-cover" src="/image.jpg" alt="Card image">
<div class="px-6 py-4">
<div class="font-bold text-xl mb-2 text-gray-800">卡片标题</div>
<p class="text-gray-600 text-base">
这是卡片的描述文本,可以放置任何内容。
</p>
</div>
<div class="px-6 pt-4 pb-2">
<span class="inline-block bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded-full mr-2">
标签1
</span>
<span class="inline-block bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full">
标签2
</span>
</div>
</div>
<!-- 2. 响应式导航栏 -->
<nav class="bg-white shadow-md">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex items-center">
<span class="text-xl font-bold text-blue-600">Logo</span>
</div>
<div class="hidden md:flex space-x-8">
<a href="#" class="text-gray-700 hover:text-blue-600 transition">首页</a>
<a href="#" class="text-gray-700 hover:text-blue-600 transition">关于</a>
<a href="#" class="text-gray-700 hover:text-blue-600 transition">联系</a>
</div>
<button class="md:hidden text-gray-700">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 6h16M4 12h16M4 18h16"></path>
</svg>
</button>
</div>
</div>
</nav>
<!-- 3. 表单输入框 -->
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
<input
type="text"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2
focus:ring-blue-500 focus:border-transparent outline-none transition"
placeholder="请输入用户名"
>
</div>
<button
class="w-full bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700
active:bg-blue-800 transition duration-200 font-medium"
>
提交
</button>
</div>
<!-- 4. 网格布局 -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 p-6">
<div class="bg-white p-6 rounded-lg shadow">卡片1</div>
<div class="bg-white p-6 rounded-lg shadow">卡片2</div>
<div class="bg-white p-6 rounded-lg shadow">卡片3</div>
</div>
对比Bootstrap
| 特性 | Tailwind CSS | Bootstrap |
|---|---|---|
| 设计理念 | 原子化类名 | 预制组件 |
| 定制性 | ⭐⭐⭐⭐⭐ 极高 | ⭐⭐⭐ 中等 |
| 学习曲线 | 中等(需记忆类名) | 简单 |
| 包体积 | 可优化至~10KB | ~200KB+ |
| HTML可读性 | 类名较多 | 结构清晰 |
| 适用场景 | 高定制化设计 | 快速原型、后台系统 |
10. classnames - 动态类名管理
GitHub: JedWatson/classnames ⭐ 22.5k+
npm周下载量: 2500万+
核心特性
简化条件性CSS类名拼接,告别繁琐的三元表达式。
- 简洁语法: 直观的条件类名组合
- 轻量: 仅1KB
- 框架无关: React、Vue、Angular通用
安装使用
npm install classnames
优秀示例
import classNames from 'classnames';
// 1. 基础用法
const buttonClass = classNames('btn', 'btn-primary', {
'btn-disabled': isDisabled,
'btn-loading': isLoading
});
// 结果: "btn btn-primary btn-loading" (当isLoading为true时)
// 2. React组件中的应用
function Button({ type, size, disabled, children }) {
const className = classNames(
'btn',
{
'btn-primary': type === 'primary',
'btn-secondary': type === 'secondary',
'btn-large': size === 'large',
'btn-small': size === 'small',
'btn-disabled': disabled
}
);
return (
<button className={className} disabled={disabled}>
{children}
</button>
);
}
// 3. Vue组件中的应用
<template>
<div :class="containerClasses">
<slot></slot>
</div>
</template>
<script setup>
import classNames from 'classnames';
const props = defineProps({
fluid: Boolean,
centered: Boolean,
padded: { type: Boolean, default: true }
});
const containerClasses = computed(() =>
classNames('container', {
'container-fluid': props.fluid,
'text-center': props.centered,
'p-4': props.padded
})
);
</script>
// 4. 复杂条件组合
const cardClass = classNames(
'card',
theme === 'dark' ? 'bg-gray-800 text-white' : 'bg-white text-gray-900',
{
'shadow-lg': elevation === 'high',
'shadow-md': elevation === 'medium',
'border-2 border-red-500': hasError,
'opacity-50': isDisabled
}
);
11. Animate.css - CSS动画库
GitHub: animate-css/animate.css ⭐ 80k+
npm周下载量: 150万+
核心特性
开箱即用的CSS动画库,提供丰富的预设动画效果。
- 丰富动画: 70+种动画效果
- 简单易用: 只需添加类名
- 可定制: 支持持续时间、延迟等配置
安装使用
npm install animate.css
优秀示例
<!-- 1. 基础动画 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
<div class="animate__animated animate__fadeIn">淡入效果</div>
<div class="animate__animated animate__bounce">弹跳效果</div>
<div class="animate__animated animate__slideInLeft">从左滑入</div>
<!-- 2. 控制动画参数 -->
<div class="animate__animated animate__fadeIn animate__delay-2s">
延迟2秒执行
</div>
<div class="animate__animated animate__bounce animate__duration-2s">
持续2秒
</div>
<!-- 3. Vue中使用 -->
<template>
<transition
enter-active-class="animate__animated animate__fadeIn"
leave-active-class="animate__animated animate__fadeOut"
>
<div v-if="show">内容</div>
</transition>
<button @click="toggleShow">切换</button>
</template>
<script setup>
import { ref } from 'vue';
import 'animate.css';
const show = ref(true);
const toggleShow = () => {
show.value = !show.value;
};
</script>
<!-- 4. React中使用 -->
import { useState } from 'react';
import 'animate.css';
function AnimatedComponent() {
const [visible, setVisible] = useState(true);
return (
<div>
{visible && (
<div className="animate__animated animate__zoomIn">
缩放进入
</div>
)}
<button onClick={() => setVisible(!visible)}>
切换显示
</button>
</div>
);
}
// 5. 触发动画(通过JS添加类名)
const triggerAnimation = (element, animation) => {
element.classList.add('animate__animated', animation);
// 动画结束后移除类名
element.addEventListener('animationend', () => {
element.classList.remove('animate__animated', animation);
}, { once: true });
};
// 使用
const box = document.querySelector('.box');
triggerAnimation(box, 'animate__shakeX');
六、图表可视化:数据展示利器
12. ECharts - 百度开源图表库
GitHub: apache/echarts ⭐ 60k+
npm周下载量: 150万+
核心特性
功能强大的数据可视化库,支持丰富的图表类型。
- 图表丰富: 50+种图表类型
- 双引擎: Canvas/SVG渲染
- 中文友好: 完善的中文文档
- 交互强大: 缩放、拖拽、联动
安装使用
npm install echarts
优秀示例
import * as echarts from 'echarts';
// 1. 基础柱状图
const initBarChart = () => {
const chartDom = document.getElementById('main');
const myChart = echarts.init(chartDom);
const option = {
title: { text: '销售统计' },
tooltip: { trigger: 'axis' },
xAxis: {
type: 'category',
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
},
yAxis: { type: 'value' },
series: [{
data: [120, 200, 150, 80, 70, 110, 130],
type: 'bar',
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#83bff6' },
{ offset: 1, color: '#188df0' }
])
}
}]
};
myChart.setOption(option);
// 响应式
window.addEventListener('resize', () => myChart.resize());
};
// 2. Vue中使用
<template>
<div ref="chartRef" style="width: 100%; height: 400px;"></div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';
const chartRef = ref(null);
let chart = null;
onMounted(() => {
chart = echarts.init(chartRef.value);
const option = {
title: { text: '数据趋势' },
xAxis: { type: 'category', data: ['A', 'B', 'C', 'D'] },
yAxis: { type: 'value' },
series: [{
data: [10, 20, 30, 40],
type: 'line',
smooth: true
}]
};
chart.setOption(option);
});
onUnmounted(() => {
chart?.dispose();
});
</script>
// 3. 高级图表:仪表盘
const initGauge = () => {
const option = {
series: [{
type: 'gauge',
progress: { show: true, width: 18 },
axisLine: { lineStyle: { width: 18 } },
axisTick: { show: false },
splitLine: { length: 15, lineStyle: { width: 2, color: '#999' } },
axisLabel: { distance: 25, color: '#999', fontSize: 14 },
anchor: { show: true, showAbove: true, size: 25, itemStyle: { borderWidth: 10 } },
title: { show: false },
detail: {
valueAnimation: true,
fontSize: 40,
offsetCenter: [0, '70%']
},
data: [{ value: 70 }]
}]
};
chart.setOption(option);
};
// 4. 地图可视化
const initMap = () => {
// 需要先注册地图JSON
fetch('/china.json')
.then(res => res.json())
.then(geoJson => {
echarts.registerMap('china', geoJson);
const option = {
series: [{
type: 'map',
map: 'china',
roam: true,
label: { show: true },
data: [
{ name: '北京', value: 100 },
{ name: '上海', value: 80 },
{ name: '广东', value: 60 }
]
}]
};
chart.setOption(option);
});
};
对比其他图表库
| 特性 | ECharts | Highcharts | Chart.js | AntV |
|---|---|---|---|---|
| GitHub Stars | 60k+ | 12k+ | 60k+ | 8k+ |
| 许可证 | Apache 2.0 (免费) | 商业授权 | MIT (免费) | MIT (免费) |
| 图表类型 | 60+ | 80+ | 8种 | 40+ |
| 中文文档 | ✅ 完善 | ✅ 完善 | ⚠️ 部分 | ✅ 完善 |
| IE支持 | IE8+ | IE6+ | IE10+ | IE10+ |
| 适用场景 | 国内项目首选 | 企业级/政企 | 轻量场景 | 阿里生态 |
七、框架增强工具:Vue/React Hooks
13. VueUse - Vue组合式API工具集
GitHub: vueuse/vueuse ⭐ 19.5k+
npm周下载量: 200万+
核心特性
基于Vue组合式API的工具函数集合,提供200+实用Hooks。
- 丰富功能: 状态、浏览器、传感器、动画等
- TypeScript: 完整的类型支持
- Tree-shakable: 按需引入
- SSR友好: 完美支持服务端渲染
安装使用
npm install @vueuse/core
优秀示例
<script setup>
import {
useMouse,
useDark,
useLocalStorage,
useDebounce,
useFetch,
useWindowSize
} from '@vueuse/core';
// 1. 鼠标追踪
const { x, y } = useMouse();
// 2. 暗色模式
const isDark = useDark();
const toggleDark = () => isDark.value = !isDark.value;
// 3. 本地存储(响应式)
const username = useLocalStorage('username', 'guest');
// 4. 防抖
const searchQuery = ref('');
const debouncedSearch = useDebounce(searchQuery, 500);
// 5. HTTP请求
const { data, error, execute } = useFetch('https://api.example.com/users');
// 6. 窗口尺寸
const { width, height } = useWindowSize();
</script>
<template>
<div>
<p>鼠标位置: {{ x }}, {{ y }}</p>
<p>窗口尺寸: {{ width }} x {{ height }}</p>
<button @click="toggleDark">
{{ isDark ? '切换到亮色' : '切换到暗色' }}
</button>
<input v-model="username" placeholder="用户名" />
<p>保存的用户名: {{ username }}</p>
<input v-model="searchQuery" placeholder="搜索..." />
<p>防抖后的搜索: {{ debouncedSearch }}</p>
<div v-if="data">
<pre>{{ data }}</pre>
</div>
</div>
</template>
14. ahooks - React Hooks库
GitHub: alibaba/hooks ⭐ 14k+
npm周下载量: 100万+
核心特性
阿里巴巴出品的高质量React Hooks库,包含100+实用Hooks。
- 企业级质量: 大规模生产验证
- TypeScript: 完善的类型定义
- 文档详细: 中英文双语文档
- 性能优化: 经过优化的实现
安装使用
npm install ahooks
优秀示例
import {
useRequest,
useDebounce,
useLocalStorageState,
useToggle,
useScroll
} from 'ahooks';
// 1. 数据请求(自带loading、错误处理)
function UserProfile() {
const { data, loading, error } = useRequest(() =>
fetch('/api/user/profile').then(res => res.json())
);
if (loading) return <div>加载中...</div>;
if (error) return <div>加载失败: {error.message}</div>;
return <div>{data?.name}</div>;
}
// 2. 本地存储
function ThemeSwitcher() {
const [theme, setTheme] = useLocalStorageState('theme', {
defaultValue: 'light'
});
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
当前主题: {theme}
</button>
);
}
// 3. 防抖
function SearchBox() {
const [value, setValue] = useState('');
const debouncedValue = useDebounce(value, { wait: 500 });
useEffect(() => {
if (debouncedValue) {
// 执行搜索
console.log('搜索:', debouncedValue);
}
}, [debouncedValue]);
return (
<input
value={value}
onChange={e => setValue(e.target.value)}
placeholder="搜索..."
/>
);
}
// 4. 布尔值切换
function ToggleExample() {
const [state, { toggle, set, setLeft, setRight }] = useToggle();
return (
<div>
<p>状态: {state ? '开' : '关'}</p>
<button onClick={toggle}>切换</button>
<button onClick={() => set(true)}>开启</button>
<button onClick={() => set(false)}>关闭</button>
</div>
);
}
// 5. 滚动监听
function ScrollTracker() {
const scroll = useScroll(document);
return (
<div>
<p>滚动位置: X={scroll?.left}, Y={scroll?.top}</p>
<div style={{ height: '2000px' }}>长内容...</div>
</div>
);
}
八、存储与缓存
15. js-cookie - Cookie操作库
GitHub: js-cookie/js-cookie ⭐ 21k+
npm周下载量: 800万+
核心特性
简单轻量的Cookie操作库。
- API简洁: 读写删一行代码
- 编码处理: 自动处理特殊字符
- 过期时间: 灵活设置有效期
安装使用
npm install js-cookie
优秀示例
import Cookies from 'js-cookie';
// 1. 设置Cookie
Cookies.set('username', '张三');
Cookies.set('token', 'abc123', { expires: 7 }); // 7天过期
Cookies.set('theme', 'dark', {
expires: 30,
path: '',
domain: '.example.com',
secure: true
});
// 2. 读取Cookie
const username = Cookies.get('username'); // '张三'
const allCookies = Cookies.get(); // { username: '张三', token: 'abc123' }
// 3. 删除Cookie
Cookies.remove('username');
Cookies.remove('token', { path: '' }); // 指定路径删除
// 4. 配合JSON
const user = { name: '张三', age: 25 };
Cookies.set('user', JSON.stringify(user));
const storedUser = JSON.parse(Cookies.get('user'));
// 5. Vue中使用
<script setup>
import { ref, onMounted } from 'vue';
import Cookies from 'js-cookie';
const theme = ref(Cookies.get('theme') || 'light');
const toggleTheme = () => {
theme.value = theme.value === 'light' ? 'dark' : 'light';
Cookies.set('theme', theme.value, { expires: 365 });
};
</script>
总结
选型建议
- 通用工具: Lodash是首选,Day.js处理日期
- 网络请求: Axios成熟稳定,新兴项目可考虑ofetch或alova
- 数据校验: TypeScript项目强烈推荐Zod
- 文件处理: SheetJS处理Excel,JSZip+FileSaver处理ZIP
- UI样式: 高定制化选Tailwind,快速开发选Bootstrap
- 图表: 国内项目ECharts,企业级Highcharts,轻量Chart.js
- Hooks: Vue用VueUse,React用ahooks或react-use
最佳实践
- 按需引入: 避免全量引入,减小打包体积
- 版本锁定: 生产环境锁定小版本号
- 类型安全: 优先选择TypeScript友好的库
- 定期更新: 关注安全更新和新特性
- 性能监控: 关键路径使用时监控性能