npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

chic-core

v1.0.3

Published

A collection of commonly used utility functions for Vue.js projects

Readme

Chic Core

一个专为Vue项目开发设计的常用工具函数库,提供丰富的JavaScript工具函数,让您的开发更加高效。

✨ 特性

  • 🚀 轻量级 - 无依赖,体积小
  • 📦 模块化 - 按需导入,支持Tree Shaking
  • 🔧 TypeScript - 完整的TypeScript类型定义
  • 🧪 测试覆盖 - 完整的单元测试
  • 📱 Vue友好 - 专为Vue项目优化
  • 🌍 浏览器兼容 - 支持现代浏览器

📦 安装

npm install chic-core
# 或
yarn add chic-core
# 或
pnpm add chic-core

🚀 快速开始

完整导入

import ChicCore from 'chic-core';

// 使用工具函数
ChicCore.formatDate(new Date());
ChicCore.capitalize('hello world');
ChicCore.unique([1, 2, 2, 3]);

按需导入

import { formatDate, capitalize, unique } from 'chic-core';

// 使用工具函数
formatDate(new Date());
capitalize('hello world');
unique([1, 2, 2, 3]);

模块导入

import { dateUtils, stringUtils, arrayUtils } from 'chic-core';

// 使用模块中的函数
dateUtils.formatDate(new Date());
stringUtils.capitalize('hello world');
arrayUtils.unique([1, 2, 2, 3]);

📚 API 文档

HTTP请求工具 (httpUtils)

createHttpClient(config?)

创建HTTP客户端

import { createHttpClient } from 'chic-core';

// 创建自定义客户端
const client = createHttpClient({
  baseURL: 'https://api.example.com',
  timeout: 10000,
  enableCache: true,
  enableLogging: true
});

// 使用客户端
const response = await client.get('/api/users');

请求方法

import { httpClient } from 'chic-core';

// GET请求
const users = await httpClient.get('/api/users', { page: 1, limit: 10 });

// POST请求
const newUser = await httpClient.post('/api/users', {
  name: 'John Doe',
  email: '[email protected]'
});

// PUT请求
const updatedUser = await httpClient.put('/api/users/1', {
  name: 'Jane Doe'
});

// DELETE请求
await httpClient.delete('/api/users/1');

文件上传和下载

import { httpClient } from 'chic-core';

// 文件上传
const formData = new FormData();
formData.append('file', file);

const uploadResponse = await httpClient.upload('/api/upload', formData, {
  onProgress: (percent, event) => {
    console.log(`上传进度: ${percent}%`);
  }
});

// 文件下载
const downloadResponse = await httpClient.download('/api/download/file.pdf', {
  onProgress: (percent, event) => {
    console.log(`下载进度: ${percent}%`);
  }
});

批量请求

import { httpClient } from 'chic-core';

const requests = [
  { method: 'get', url: '/api/users/1' },
  { method: 'get', url: '/api/users/2' },
  { method: 'get', url: '/api/users/3' }
];

const result = await httpClient.batch(requests, {
  concurrency: 2, // 并发数
  failFast: false // 是否快速失败
});

console.log(`成功: ${result.successCount}, 失败: ${result.errorCount}`);

请求拦截器

import { createHttpClient } from 'chic-core';

const client = createHttpClient();

// 请求拦截器
client.config.addRequestInterceptor((config) => {
  // 添加认证token
  config.headers.Authorization = `Bearer ${getToken()}`;
  return config;
});

// 响应拦截器
client.config.addResponseInterceptor((response) => {
  // 处理响应数据
  if (response.data.code === 0) {
    return response.data.data;
  }
  throw new Error(response.data.message);
});

// 错误处理器
client.config.addErrorHandler(401, (error) => {
  // 处理401错误,跳转到登录页
  window.location.href = '/login';
});

高级配置

import { createHttpClient, HttpConfig } from 'chic-core';

const config = new HttpConfig()
  .setBaseURL('https://api.example.com')
  .setTimeout(15000)
  .setRetry(3, 1000, 2) // 重试3次,延迟1秒,退避倍数2
  .setCache(true, 300000) // 启用缓存,5分钟过期
  .setAuth('token', 'refreshToken', '/refresh') // 设置认证
  .addErrorHandler(404, (error) => {
    console.log('资源未找到');
  });

const client = new HttpClient(config);

日期工具 (dateUtils)

formatDate(date, format?)

格式化日期为指定格式

import { formatDate } from 'chic-core';

formatDate(new Date()); // '2023-12-25 10:30:00'
formatDate(new Date(), 'YYYY-MM-DD'); // '2023-12-25'

getRelativeTime(date)

获取相对时间描述

import { getRelativeTime } from 'chic-core';

getRelativeTime(new Date(Date.now() - 60000)); // '1分钟前'

isToday(date)

判断是否为今天

import { isToday } from 'chic-core';

isToday(new Date()); // true

字符串工具 (stringUtils)

capitalize(str)

首字母大写

import { capitalize } from 'chic-core';

capitalize('hello world'); // 'Hello world'

camelCase(str)

转换为驼峰命名

import { camelCase } from 'chic-core';

camelCase('hello world'); // 'helloWorld'

kebabCase(str)

转换为短横线命名

import { kebabCase } from 'chic-core';

kebabCase('helloWorld'); // 'hello-world'

isEmail(email)

验证邮箱格式

import { isEmail } from 'chic-core';

isEmail('[email protected]'); // true

数组工具 (arrayUtils)

unique(arr)

数组去重

import { unique } from 'chic-core';

unique([1, 2, 2, 3]); // [1, 2, 3]

groupBy(arr, key)

数组分组

import { groupBy } from 'chic-core';

const users = [
  { name: 'John', age: 20 },
  { name: 'Jane', age: 20 },
  { name: 'Bob', age: 30 }
];

groupBy(users, 'age');
// { '20': [{ name: 'John', age: 20 }, { name: 'Jane', age: 20 }], '30': [{ name: 'Bob', age: 30 }] }

sortBy(arr, key, order)

数组排序

import { sortBy } from 'chic-core';

const users = [
  { name: 'John', age: 30 },
  { name: 'Jane', age: 20 }
];

sortBy(users, 'age', 'asc');
// [{ name: 'Jane', age: 20 }, { name: 'John', age: 30 }]

对象工具 (objectUtils)

deepClone(obj)

深拷贝对象

import { deepClone } from 'chic-core';

const obj = { a: 1, b: { c: 2 } };
const cloned = deepClone(obj);

merge(target, ...sources)

对象合并

import { merge } from 'chic-core';

const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
merge(obj1, obj2); // { a: 1, b: 3, c: 4 }

get(obj, path, defaultValue)

获取对象属性值

import { get } from 'chic-core';

const obj = { a: { b: { c: 1 } } };
get(obj, 'a.b.c'); // 1
get(obj, 'a.b.d', 'default'); // 'default'

验证工具 (validateUtils)

validateForm(data, rules)

表单验证

import { validateForm } from 'chic-core';

const data = { email: '[email protected]', age: 25 };
const rules = {
  email: [
    { type: 'required', message: '邮箱不能为空' },
    { type: 'email', message: '邮箱格式不正确' }
  ],
  age: [
    { type: 'required', message: '年龄不能为空' },
    { type: 'range', min: 18, max: 100, message: '年龄必须在18-100之间' }
  ]
};

const result = validateForm(data, rules);
// { isValid: true, errors: {} }

存储工具 (storageUtils)

localStorage 操作

import { setLocalStorage, getLocalStorage, removeLocalStorage } from 'chic-core';

setLocalStorage('user', { name: 'John', age: 25 });
const user = getLocalStorage('user');
removeLocalStorage('user');

StorageManager 类

import { StorageManager } from 'chic-core';

const storage = new StorageManager(localStorage);
storage.set('key', 'value');
const value = storage.get('key');

DOM工具 (domUtils)

元素选择

import { $, $$ } from 'chic-core';

const element = $('.my-class');
const elements = $$('.my-class');

类名操作

import { addClass, removeClass, toggleClass, hasClass } from 'chic-core';

const element = document.querySelector('.my-class');
addClass(element, 'active');
removeClass(element, 'inactive');
toggleClass(element, 'visible');
hasClass(element, 'active'); // true

防抖和节流

import { debounce, throttle } from 'chic-core';

const debouncedFn = debounce(() => {
  console.log('防抖函数');
}, 300);

const throttledFn = throttle(() => {
  console.log('节流函数');
}, 300);

文件工具 (fileUtils)

downloadFile(data, filename, mimeType?)

下载文件

import { downloadFile } from 'chic-core';

// 下载文本文件
downloadFile('Hello World', 'hello.txt', 'text/plain');

// 下载Blob文件
const blob = new Blob(['content'], { type: 'text/plain' });
downloadFile(blob, 'file.txt');

uploadFile(file, url, options?)

文件上传

import { uploadFile } from 'chic-core';

const file = document.querySelector('input[type="file"]').files[0];
uploadFile(file, '/api/upload', {
  onProgress: (progress) => console.log(`上传进度: ${progress}%`),
  onSuccess: (response) => console.log('上传成功:', response),
  onError: (error) => console.error('上传失败:', error)
});

previewImage(file, options?)

图片预览

import { previewImage } from 'chic-core';

const file = document.querySelector('input[type="file"]').files[0];
previewImage(file, {
  maxWidth: 800,
  maxHeight: 600,
  quality: 0.8
}).then(result => {
  console.log('预览结果:', result);
});

validateFile(file, options?)

文件验证

import { validateFile } from 'chic-core';

const file = document.querySelector('input[type="file"]').files[0];
const result = validateFile(file, {
  allowedTypes: ['image/jpeg', 'image/png'],
  maxSize: 5 * 1024 * 1024, // 5MB
  allowedExtensions: ['jpg', 'jpeg', 'png']
});

if (result.isValid) {
  console.log('文件验证通过');
} else {
  console.log('验证失败:', result.errors);
}

createFileDropZone(element, options?)

创建拖拽上传区域

import { createFileDropZone } from 'chic-core';

const dropZone = document.getElementById('drop-zone');
const controller = createFileDropZone(dropZone, {
  onDrop: (files) => console.log('拖拽文件:', files),
  onDragOver: () => console.log('拖拽进入'),
  multiple: true,
  accept: ['jpg', 'png', 'pdf']
});

// 清理
controller.destroy();

格式化工具 (formatUtils)

数字格式化

import { formatNumber, formatCurrency } from 'chic-core';

formatNumber(1234.56); // '1,234.56'
formatCurrency(1234.56, '¥'); // '¥1,234.56'

文件大小格式化

import { formatFileSize } from 'chic-core';

formatFileSize(1024); // '1 KB'
formatFileSize(1048576); // '1 MB'

🧪 测试

# 运行测试
npm test

# 监听模式
npm run test:watch

# 生成覆盖率报告
npm run test -- --coverage

🔧 开发

# 安装依赖
npm install

# 开发模式
npm run dev

# 构建
npm run build

# 代码检查
npm run lint

# 修复代码
npm run lint:fix

📦 构建产物

  • dist/index.js - CommonJS 格式
  • dist/index.esm.js - ES Module 格式
  • dist/index.umd.js - UMD 格式
  • dist/index.umd.min.js - UMD 压缩格式
  • dist/index.d.ts - TypeScript 类型定义

🌍 浏览器支持

  • Chrome >= 60
  • Firefox >= 60
  • Safari >= 12
  • Edge >= 79

📄 许可证

MIT License

🤝 贡献

欢迎提交 Issue 和 Pull Request!

📞 联系方式

如有问题,请通过以下方式联系:


⭐ 如果这个项目对您有帮助,请给它一个星标!