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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@cimom/vben-utils

v5.6.3

Published

用于多个 `app` 公用的工具包,继承了 `@cimom/vben-core-shared/utils` 的所有能力。业务上有通用的工具函数可以放在这里。

Readme

@cimom/vben-utils

用于多个 app 公用的工具包,继承了 @cimom/vben-core-shared/utils 的所有能力。业务上有通用的工具函数可以放在这里。

安装

# 进入目标应用目录,例如 apps/xxxx-app
# cd apps/xxxx-app
pnpm add @cimom/vben-utils

基本使用

// 导入单个工具函数
import { isString, findMenuByPath } from '@cimom/vben-utils';

// 使用工具函数
if (isString('test')) {
  console.log('This is a string');
}

// 查找菜单
const menu = findMenuByPath(menuList, '/dashboard');

可用工具函数

菜单和路由工具

该包提供了一系列与菜单和路由相关的工具函数:

findMenuByPath

根据路径在菜单列表中查找菜单项。

import { findMenuByPath } from '@cimom/vben-utils';

const menus = [
  {
    path: '/dashboard',
    title: '仪表盘',
    children: [
      {
        path: '/dashboard/analysis',
        title: '分析页',
      },
    ],
  },
];

// 查找菜单项
const menu = findMenuByPath(menus, '/dashboard/analysis');
// 返回: { path: '/dashboard/analysis', title: '分析页' }

findRootMenuByPath

根据路径在菜单列表中查找根菜单项。

import { findRootMenuByPath } from '@cimom/vben-utils';

const { findMenu, rootMenu, rootMenuPath } = findRootMenuByPath(
  menus,
  '/dashboard/analysis',
);
// findMenu: 当前菜单项
// rootMenu: 根菜单项
// rootMenuPath: 根菜单路径

generateMenus

根据路由配置生成菜单列表。

import { generateMenus } from '@cimom/vben-utils';
import { createRouter } from 'vue-router';

const router = createRouter(/* ... */);
const routes = router.getRoutes();

// 生成菜单列表
const menus = generateMenus(routes, router);

generateRoutesFromBackend

根据后端返回的菜单数据生成路由配置。

import { generateRoutesFromBackend } from '@cimom/vben-utils';

// 从后端获取的菜单数据
const backendMenus = [
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: 'LAYOUT',
    meta: {
      title: '仪表盘',
      icon: 'dashboard',
    },
    children: [
      {
        path: 'analysis',
        name: 'Analysis',
        component: '/dashboard/analysis/index',
        meta: {
          title: '分析页',
        },
      },
    ],
  },
];

// 生成路由配置
const routes = generateRoutesFromBackend(backendMenus);

generateRoutesFromFrontend

根据前端定义的模块生成路由配置。

import { generateRoutesFromFrontend } from '@cimom/vben-utils';

// 前端路由模块
const modules = import.meta.glob('./modules/**/*.ts', { eager: true });

// 生成路由配置
const routes = generateRoutesFromFrontend(modules);

mergeRouteModules

合并多个路由模块。

import { mergeRouteModules } from '@cimom/vben-utils';

// 合并路由模块
const routes = mergeRouteModules(modules);

resetRoutes

重置路由配置。

import { resetRoutes } from '@cimom/vben-utils';
import { createRouter } from 'vue-router';

const router = createRouter(/* ... */);

// 重置路由
resetRoutes(router);

其他工具函数

getPopupContainer

获取弹出层的容器元素。

import { getPopupContainer } from '@cimom/vben-utils';

// 在 Ant Design Vue 组件中使用
<a-select :getPopupContainer="getPopupContainer" />

unmountGlobalLoading

卸载全局加载提示。

import { unmountGlobalLoading } from '@cimom/vben-utils';

// 在应用启动完成后调用
unmountGlobalLoading();

继承的核心工具函数

该包继承了 @cimom/vben-core-shared/utils 中的所有工具函数,下面是一些常用的核心工具函数:

类型判断函数

import {
  isArray,
  isBoolean,
  isDate,
  isFunction,
  isNull,
  isNumber,
  isObject,
  isString,
  isUndefined,
} from '@cimom/vben-utils';

// 使用示例
isString('test'); // true
isNumber(123); // true
isArray([1, 2, 3]); // true
isObject({}); // true
isFunction(() => {}); // true
isBoolean(true); // true
isDate(new Date()); // true
isNull(null); // true
isUndefined(undefined); // true

对象操作函数

import { deepMerge, omit, pick, sortObject } from '@cimom/vben-utils';

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

// 从对象中排除指定属性
const newObj = omit({ a: 1, b: 2, c: 3 }, ['a', 'c']);
// 结果: { b: 2 }

// 从对象中选取指定属性
const picked = pick({ a: 1, b: 2, c: 3 }, ['a', 'c']);
// 结果: { a: 1, c: 3 }

// 对象排序
const sorted = sortObject({ c: 3, a: 1, b: 2 });
// 结果: { a: 1, b: 2, c: 3 }

数组操作函数

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

const tree = [
  {
    id: 1,
    name: 'Node 1',
    children: [
      {
        id: 2,
        name: 'Node 1.1',
      },
      {
        id: 3,
        name: 'Node 1.2',
      },
    ],
  },
];

// 过滤树结构
const filteredTree = filterTree(tree, (node) => node.id !== 2);

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

// 映射树结构
const mappedTree = mapTree(tree, (node) => ({
  ...node,
  title: node.name,
}));

// 树转列表
const list = treeToList(tree);

字符串操作函数

import { camelCase, kebabCase, pascalCase, snakeCase } from '@cimom/vben-utils';

// 转换为驼峰命名
camelCase('hello-world'); // 'helloWorld'

// 转换为短横线命名
kebabCase('helloWorld'); // 'hello-world'

// 转换为帕斯卡命名
pascalCase('hello-world'); // 'HelloWorld'

// 转换为下划线命名
snakeCase('helloWorld'); // 'hello_world'

缓存相关函数

该包还继承了 @cimom/vben-core-shared/cache 中的缓存相关函数:

import {
  createLocalStorage,
  createSessionStorage,
  createMemoryStorage,
} from '@cimom/vben-utils';

// 创建本地存储
const ls = createLocalStorage();
ls.set('key', 'value');
ls.get('key'); // 'value'
ls.remove('key');
ls.clear();

// 创建会话存储
const ss = createSessionStorage();

// 创建内存存储
const ms = createMemoryStorage();

颜色相关函数

该包还继承了 @cimom/vben-core-shared/color 中的颜色相关函数:

import { darken, lighten, rgbToHex, hexToRgb } from '@cimom/vben-utils';

// 颜色加深
darken('#3080E8', 0.2); // '#1060C8'

// 颜色变浅
lighten('#3080E8', 0.2); // '#50A0FF'

// RGB 转 16 进制
rgbToHex('rgb(48, 128, 232)'); // '#3080E8'

// 16 进制转 RGB
hexToRgb('#3080E8'); // 'rgb(48, 128, 232)'

使用示例

在 Vue 组件中使用

<template>
  <div>
    <h1>{{ title }}</h1>
    <ul>
      <li v-for="item in menuItems" :key="item.path">
        {{ item.title }}
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { generateMenus, isString } from '@cimom/vben-utils';

const router = useRouter();
const title = ref('');
const menuItems = ref([]);

onMounted(() => {
  // 生成菜单
  const routes = router.getRoutes();
  menuItems.value = generateMenus(routes, router);

  // 类型判断
  const titleValue = 'Dashboard';
  if (isString(titleValue)) {
    title.value = titleValue;
  }
});
</script>

在路由配置中使用

import { createRouter, createWebHistory } from 'vue-router';
import { generateRoutesFromFrontend, resetRoutes } from '@cimom/vben-utils';

// 动态导入路由模块
const modules = import.meta.glob('./modules/**/*.ts', { eager: true });

// 生成路由配置
const routes = generateRoutesFromFrontend(modules);

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 重置路由
function resetRouter() {
  resetRoutes(router);
}

export { router, resetRouter };

使用缓存工具

import { createLocalStorage } from '@cimom/vben-utils';

// 创建本地存储实例
const ls = createLocalStorage({
  prefixKey: 'my-app_',
  encryption: true,
  encryptionKey: 'my-secret-key',
});

// 存储数据
ls.set('user', { id: 1, name: 'Admin' });

// 获取数据
const user = ls.get('user');
console.log(user); // { id: 1, name: 'Admin' }

// 移除数据
ls.remove('user');

// 清空所有数据
ls.clear();

注意事项

  • 该包主要用于共享工具函数,应避免在其中包含特定于某个应用的业务逻辑。
  • 引入该包会自动引入 @cimom/vben-core-shared/utils@cimom/vben-core-shared/cache@cimom/vben-core-shared/color 中的所有工具函数。
  • 如果需要添加新的工具函数,建议在 helpers 目录下创建新的文件,然后在 helpers/index.ts 中导出。