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

@cimom/vben-core-shared

v5.6.8

Published

该包提供了 Vue Vben Admin 项目的核心共享工具和功能,包括常量、工具函数、缓存管理、颜色处理、状态管理等基础功能。它是整个项目的基础设施,为其他模块提供了通用的功能支持。

Downloads

79

Readme

@cimom/vben-core-shared

该包提供了 Vue Vben Admin 项目的核心共享工具和功能,包括常量、工具函数、缓存管理、颜色处理、状态管理等基础功能。它是整个项目的基础设施,为其他模块提供了通用的功能支持。

安装

pnpm add @cimom/vben-core-shared

包含模块

该包采用子路径导出的方式,按功能模块组织代码,可以按需引入所需的模块:

  • @cimom/vben-core-shared/constants - 全局常量
  • @cimom/vben-core-shared/utils - 工具函数
  • @cimom/vben-core-shared/color - 颜色处理工具
  • @cimom/vben-core-shared/cache - 缓存管理
  • @cimom/vben-core-shared/store - 状态存储
  • @cimom/vben-core-shared/global-state - 全局状态管理

基本使用

常量模块

import {
  APP_NAME,
  VBEN_KEY,
  DEFAULT_LOCALE,
} from '@cimom/vben-core-shared/constants';

console.log('应用名称:', APP_NAME);
console.log('默认语言:', DEFAULT_LOCALE);

工具函数

import {
  cloneDeep,
  isEqual,
  get,
  set,
  formatDate,
  downloadByUrl,
  deepMerge,
} from '@cimom/vben-core-shared/utils';

// 深拷贝对象
const original = { a: 1, b: { c: 2 } };
const copy = cloneDeep(original);

// 对象比较
const isEqualResult = isEqual(original, copy); // true

// 安全获取嵌套属性
const value = get(original, 'b.c'); // 2

// 安全设置嵌套属性
set(original, 'b.d', 3);

// 日期格式化
const formattedDate = formatDate(new Date(), 'YYYY-MM-DD');

// 下载文件
downloadByUrl('https://example.com/file.pdf', 'document.pdf');

// 深度合并对象
const merged = deepMerge({ a: 1, b: { c: 2 } }, { b: { d: 3 }, e: 4 });
// 结果: { a: 1, b: { c: 2, d: 3 }, e: 4 }

颜色处理

import {
  generateColors,
  darken,
  lighten,
  getColorPalette,
  isHexColor,
} from '@cimom/vben-core-shared/color';

// 检查是否为有效的十六进制颜色
const isValid = isHexColor('#1890ff'); // true

// 生成暗色变体
const darkColor = darken('#1890ff', 10); // 暗化 10%

// 生成亮色变体
const lightColor = lighten('#1890ff', 10); // 亮化 10%

// 生成调色板
const palette = getColorPalette('#1890ff', 10);

// 生成主题色系
const themeColors = generateColors('#1890ff');

缓存管理

import {
  createLocalStorage,
  createSessionStorage,
  createMemoryStorage,
} from '@cimom/vben-core-shared/cache';

// 创建本地存储实例
const ls = createLocalStorage();
ls.set('user', { id: 1, name: 'Admin' });
const user = ls.get('user');
ls.remove('user');
ls.clear();

// 创建会话存储实例
const ss = createSessionStorage();
ss.set('token', 'abc123');
const token = ss.get('token');

// 创建内存存储实例
const ms = createMemoryStorage();
ms.set('tempData', { value: 123 });
const tempData = ms.get('tempData');

全局状态管理

import { createGlobalState } from '@cimom/vben-core-shared/global-state';

// 创建全局状态
const { state, setState, subscribe, reset } = createGlobalState({
  count: 0,
  user: null,
  theme: 'light',
});

// 获取状态
console.log(state.count); // 0

// 更新状态
setState({ count: state.count + 1 });

// 订阅状态变化
const unsubscribe = subscribe((newState, oldState) => {
  console.log('状态已更新:', newState, oldState);
});

// 重置状态
reset();

// 取消订阅
unsubscribe();

模块详解

常量模块 (constants)

提供全局常量定义,包括:

  • 应用名称和版本
  • 存储键名
  • 默认配置
  • 环境变量
  • 路由常量
  • 事件名称
// 全局常量
export const APP_NAME = 'Vben Admin';
export const APP_VERSION = '5.5.8';
export const DEFAULT_LOCALE = 'zh-CN';

// 存储键名
export const VBEN_KEY = {
  TOKEN: 'TOKEN',
  LOCALE: 'LOCALE',
  THEME: 'THEME',
  USER_INFO: 'USER_INFO',
  TABS: 'TABS',
  PERMISSIONS: 'PERMISSIONS',
};

// 其他常量...

工具函数 (utils)

提供各种实用工具函数,包括:

日期处理

import {
  formatDate,
  formatToDateTime,
  dateUtil,
} from '@cimom/vben-core-shared/utils';

// 格式化日期
formatDate(new Date(), 'YYYY-MM-DD'); // 2025-05-27

// 格式化为日期时间
formatToDateTime(new Date()); // 2025-05-27 17:30:45

// 使用 dayjs 实例
dateUtil().format('YYYY/MM/DD'); // 2025/05/27

DOM 操作

import {
  addClass,
  removeClass,
  hasClass,
  getStyle,
} from '@cimom/vben-core-shared/utils';

// 添加类名
addClass(element, 'active');

// 移除类名
removeClass(element, 'active');

// 检查是否包含类名
const has = hasClass(element, 'active');

// 获取样式
const color = getStyle(element, 'color');

下载工具

import { downloadByUrl, downloadByData } from '@cimom/vben-core-shared/utils';

// 通过 URL 下载
downloadByUrl('https://example.com/file.pdf', 'document.pdf');

// 通过 Blob 数据下载
const blob = new Blob(['content'], { type: 'text/plain' });
downloadByData(blob, 'text.txt');

树形结构处理

import {
  mapTree,
  filterTree,
  findTreeNode,
} from '@cimom/vben-core-shared/utils';

// 映射树
const newTree = mapTree(tree, (node) => ({
  ...node,
  title: `Item: ${node.title}`,
}));

// 过滤树
const filteredTree = filterTree(tree, (node) => node.visible !== false);

// 查找节点
const node = findTreeNode(tree, (node) => node.id === 10);

其他工具

import {
  deepMerge,
  unique,
  isEqual,
  cloneDeep,
  startNProgress,
  doneNProgress,
} from '@cimom/vben-core-shared/utils';

// 深度合并
const merged = deepMerge(obj1, obj2);

// 数组去重
const uniqueArray = unique([1, 2, 2, 3, 3, 4]);

// 进度条
startNProgress();
// 操作完成后
doneNProgress();

颜色处理 (color)

提供颜色处理和转换功能:

import {
  isHexColor,
  darken,
  lighten,
  getColorPalette,
  generateColors,
} from '@cimom/vben-core-shared/color';

// 检查是否为有效的十六进制颜色
const isValid = isHexColor('#1890ff'); // true

// 生成暗色变体
const darkColor = darken('#1890ff', 10); // 暗化 10%

// 生成亮色变体
const lightColor = lighten('#1890ff', 10); // 亮化 10%

// 生成调色板
const palette = getColorPalette('#1890ff', 10);
// 返回包含 10 个不同深浅度的颜色数组

// 生成主题色系
const themeColors = generateColors('#1890ff');
// 返回包含主色、成功色、警告色、错误色等的对象

缓存管理 (cache)

提供多种缓存存储方式:

import {
  createLocalStorage,
  createSessionStorage,
  createMemoryStorage,
} from '@cimom/vben-core-shared/cache';

// 创建本地存储实例
const ls = createLocalStorage({
  prefixKey: 'vben_', // 键名前缀
  timeout: 60 * 60 * 24 * 7, // 过期时间(秒)
});

// 设置值
ls.set('user', { id: 1, name: 'Admin' });

// 获取值
const user = ls.get('user');

// 获取值,如果不存在则返回默认值
const config = ls.get('config', { theme: 'light' });

// 移除值
ls.remove('user');

// 清空所有值
ls.clear();

// 会话存储和内存存储的用法类似

全局状态管理 (global-state)

提供简单的全局状态管理功能:

import { createGlobalState } from '@cimom/vben-core-shared/global-state';

// 创建全局状态
const {
  state, // 状态对象(响应式)
  setState, // 更新状态函数
  getState, // 获取状态函数
  subscribe, // 订阅状态变化
  reset, // 重置状态函数
} = createGlobalState({
  count: 0,
  user: null,
  theme: 'light',
});

// 获取状态
console.log(state.count); // 0
// 或者
const currentState = getState();

// 更新状态(部分更新)
setState({ count: state.count + 1 });

// 订阅状态变化
const unsubscribe = subscribe((newState, oldState) => {
  console.log('状态已更新:', newState, oldState);
});

// 重置状态到初始值
reset();

// 取消订阅
unsubscribe();

高级用法

自定义缓存前缀和过期时间

import { createLocalStorage } from '@cimom/vben-core-shared/cache';

// 创建自定义配置的本地存储
const appStorage = createLocalStorage({
  prefixKey: 'myapp_',
  timeout: 60 * 60 * 24, // 1天过期
});

// 为特定项设置自定义过期时间
appStorage.set('session', { token: 'abc123' }, 60 * 30); // 30分钟过期

结合 Vue 使用全局状态

import { createGlobalState } from '@cimom/vben-core-shared/global-state';
import { computed, onUnmounted } from 'vue';

export function useAppState() {
  const { state, setState, subscribe, reset } = createGlobalState({
    loading: false,
    user: null,
    notifications: [],
  });

  // 计算属性
  const isLoggedIn = computed(() => !!state.user);
  const notificationCount = computed(() => state.notifications.length);

  // 方法
  function setLoading(loading) {
    setState({ loading });
  }

  function setUser(user) {
    setState({ user });
  }

  function addNotification(notification) {
    setState({
      notifications: [...state.notifications, notification],
    });
  }

  // 订阅状态变化
  const unsubscribe = subscribe((newState) => {
    console.log('应用状态已更新:', newState);
  });

  // 组件卸载时取消订阅
  onUnmounted(() => {
    unsubscribe();
  });

  return {
    state,
    isLoggedIn,
    notificationCount,
    setLoading,
    setUser,
    addNotification,
    reset,
  };
}

创建主题色系统

import {
  generateColors,
  updateCssVariables,
} from '@cimom/vben-core-shared/color';
import { createLocalStorage } from '@cimom/vben-core-shared/cache';

// 创建主题管理器
export function useThemeManager() {
  const storage = createLocalStorage();

  // 设置主题色
  function setThemeColor(color) {
    // 生成主题色系
    const colors = generateColors(color);

    // 更新 CSS 变量
    updateCssVariables(colors);

    // 保存到本地存储
    storage.set('themeColor', color);
  }

  // 初始化主题
  function initTheme() {
    const savedColor = storage.get('themeColor');
    if (savedColor) {
      setThemeColor(savedColor);
    }
  }

  return {
    setThemeColor,
    initTheme,
  };
}

与其他包的关系

  • @cimom/vben-utils: 基于此包的工具函数构建,提供了更高级别的工具封装。
  • @cimom/vben-constants: 基于此包的常量模块构建,提供了更多特定于应用的常量。
  • @cimom/vben-stores: 基于此包的状态管理功能构建,提供了更完整的状态管理解决方案。
  • @cimom/vben-preferences: 使用此包的缓存和状态管理功能实现偏好设置的存储和管理。

注意事项

  1. 该包是核心基础设施,被多个其他包依赖,修改时需谨慎。
  2. 缓存模块的数据会根据配置的过期时间自动失效,确保关键数据有适当的备份策略。
  3. 全局状态不是响应式的,如果需要响应式状态管理,建议结合 Vue 的响应式系统使用。

常见问题

缓存数据丢失

可能的原因:

  1. 数据已过期
  2. 浏览器存储被清除
  3. 键名前缀不一致

解决方案:

// 检查存储是否可用
function checkStorage() {
  try {
    localStorage.setItem('test', 'test');
    localStorage.removeItem('test');
    return true;
  } catch (e) {
    return false;
  }
}

// 使用一致的前缀
const storage = createLocalStorage({ prefixKey: 'vben_' });

// 为关键数据设置更长的过期时间或不过期
storage.set('important_data', data, null); // 永不过期

全局状态管理与 Vuex/Pinia 的区别

createGlobalState 提供的是一个轻量级的状态管理解决方案,适用于简单场景:

  1. 不依赖 Vue,可以在任何 JavaScript 环境中使用
  2. 没有内置的模块化和中间件支持
  3. 更简单,但功能更有限

对于复杂的状态管理需求,建议使用 Vuex 或 Pinia。

在 SSR 环境中使用

在服务器端渲染环境中使用时,需要注意:

  1. 本地存储和会话存储在服务器端不可用
  2. 使用内存存储代替
import { createMemoryStorage } from '@cimom/vben-core-shared/cache';

// 检测环境
const isServer = typeof window === 'undefined';
const storage = isServer ? createMemoryStorage() : createLocalStorage();