l-js-fn
整理了常用的 JavaScript 方法,轻量级、零依赖、TypeScript 支持

✨ 特性
- 🚀 轻量级 - 零依赖,打包体积小
- 📦 模块化 - 支持按需导入,减少包体积
- 🔒 TypeScript - 完整的类型定义
- 🌐 双模块格式 - 同时支持 ESM 和 CJS
- 🎨 Tree-shaking - 完整支持 Tree-shaking,只打包用到的代码
- 💪 工具齐全 - 涵盖数组、对象、字符串、日期、URL、正则等常用操作
- 🔧 高级功能 - WebSocket 管理、轮询、IPC 通信等
📦 安装
npm install l-js-fn
yarn add l-js-fn
pnpm add l-js-fn
🚀 快速开始
导入主包(包含所有工具函数)
import { isArray, dateFormat, isEmpty } from 'l-js-fn';
isArray([1, 2, 3]);
dateFormat(new Date(), 'yyyy-MM-dd HH:mm:ss');
isEmpty('');
isEmpty(null);
按需导入(推荐)
只导入你需要的模块,减少打包体积:
import { scrollTop, copyToClipboard, launchFullscreen } from 'l-js-fn/bom';
import { Polling } from 'l-js-fn/polling';
import { WebSocketManager } from 'l-js-fn/ws';
import { REGEXP } from 'l-js-fn/regex';
import { DATE_FORMAT, HTTP_STATUS } from 'l-js-fn/config';
import { H5Bridge, IframeBridge } from 'l-js-fn/ipc';
import { escapeHTML, base64Encode } from 'l-js-fn/encode';
import { formatFileSize, isImage } from 'l-js-fn/file';
📚 API 文档
主包工具函数
类型判断 (is-kit)
import {
isEmpty,
isNotEmpty,
isObject,
isArray,
isString,
isEmail,
isURL,
isIdCard,
isPhoneNumber,
isEqual,
validateParams
} from 'l-js-fn';
isEmpty('');
isEmpty([]);
isEmpty({});
isEmail('test@example.com');
isPhoneNumber('13800138000');
isIdCard('110101199001011234');
isEqual({ a: 1 }, { a: 1 });
validateParams(['name', 'age'], { name: 'John', age: 20 });
validateParams(['name'], { age: 20 });
数组操作 (array-kit)
import {
arrayDelEl,
arrayDelToIndex,
arrayFill,
arrayUnique,
arrayPaginate,
arraySplitToGroups,
moveElement,
groupBy,
sample,
sampleSize
} from 'l-js-fn';
arrayDelEl([1, 2, 3, 2], 2);
arrayDelToIndex([1, 2, 3], 1);
arrayFill([1, 2], 5, 0);
arrayUnique([1, 2, 2, 3]);
arrayPaginate([1, 2, 3, 4, 5], 2, 2);
arraySplitToGroups([1, 2, 3, 4, 5], 2);
moveElement([1, 2, 3], 1, 'up');
groupBy([
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 30 }
], 'age');
sample([1, 2, 3, 4, 5]);
sampleSize([1, 2, 3, 4, 5], 2);
字符串处理 (string-kit)
import {
desensitization,
trim,
getMobile,
getUuid,
indexToLabel
} from 'l-js-fn';
desensitization('13800138000', 3, 4);
trim(' hello ');
trim(' hello ', 'all');
getMobile();
getUuid();
indexToLabel(0, 'upper');
indexToLabel(1, 'lower');
indexToLabel(0, 'chinese');
对象操作 (object-kit)
import {
objMerge,
objFilterProp,
objFilterNull,
jsonToFormData,
formDataToObject
} from 'l-js-fn';
objMerge({ a: 1 }, { b: 2 });
objFilterProp({ a: 1, b: 2, c: 3 }, ['b']);
objFilterNull({ a: 1, b: null, c: undefined });
jsonToFormData({ name: 'John', age: 20 });
formDataToObject(formData);
日期处理 (date-kit)
import {
dateFormat,
dateSecond,
diffDays,
formatPassTime,
monthDays,
getTimeDiff
} from 'l-js-fn';
dateFormat(new Date());
dateFormat(new Date(), 'yyyy-MM-dd');
dateSecond(3661);
diffDays('2024-01-01', '2024-01-03');
formatPassTime('2024-01-01 12:00:00');
monthDays('2024-02-01');
getTimeDiff('2024-01-01', '2024-01-02');
数字处理 (number-kit)
import {
formatNumber,
toPercent,
random,
getUniqueRandomIndexes
} from 'l-js-fn';
formatNumber(1234567);
formatNumber(1234567, true);
toPercent(0.5332);
random(10);
random(1, 10);
random(1, 10, { float: true });
getUniqueRandomIndexes(10, 3);
URL 处理 (url-kit)
import {
getUrlParams,
getUrlParam,
appendUrlParam,
transUrlParams,
getFileInfoToUrl
} from 'l-js-fn';
getUrlParams('https://example.com?id=1&name=John');
getUrlParam('https://example.com?id=1', 'id');
appendUrlParam('https://example.com', 'id', 1);
transUrlParams({ id: 1, name: 'John' });
getFileInfoToUrl('https://example.com/file.txt');
通用工具 (common)
import {
sleep,
debounce,
throttle,
getType,
deepClone,
getDevice,
imageToBase64
} from 'l-js-fn';
await sleep(1000);
const debouncedFn = debounce(() => {
console.log('执行');
}, 300);
const throttledFn = throttle(() => {
console.log('执行');
}, 300);
getType([1, 2, 3]);
getType(new Date());
deepClone({ a: { b: 1 } });
getDevice();
const result = await imageToBase64('https://example.com/image.png');
浏览器对象模型 (bom)
import {
scrollTop,
scrollToBottom,
getScrollPosition,
setScrollPosition,
launchFullscreen,
exitFullscreen,
copyToClipboard,
setCookie,
getCookie,
removeCookie,
hasCookie,
getAllCookies
} from 'l-js-fn/bom';
scrollTop();
scrollToBottom();
getScrollPosition();
setScrollPosition({ x: 0, y: 100 }, true);
await launchFullscreen(document.documentElement);
await exitFullscreen();
await copyToClipboard('要复制的文本');
setCookie('token', 'abc123', { expires: 30, secure: true });
getCookie('token');
hasCookie('token');
removeCookie('token');
getAllCookies();
本地存储 (storage)
import {
setStorage,
getStorage,
removeStorage,
clearStorage,
clearExpiredStorage,
setSession,
getSession,
removeSession
} from 'l-js-fn/storage';
setStorage('user', { name: 'John', age: 20 });
setStorage('token', 'abc123', { expire: 3600 });
getStorage('user');
getStorage('token');
removeStorage('user');
clearStorage();
clearExpiredStorage();
setSession('tabData', { id: 1, name: 'test' });
getSession('tabData');
removeSession('tabData');
WebSocket 管理 (ws)
import { WebSocketManager } from 'l-js-fn/ws';
const ws = new WebSocketManager(
'ws://localhost:8080',
(message) => console.log('收到消息:', message),
(error) => console.error('错误:', error)
);
ws.sendWebSocketMessage({ type: 'ping', data: 'hello' });
ws.checkConnection({ type: 'heartbeat' }, 10000);
ws.reconnect(5000);
ws.close();
轮询工具 (polling)
import { Polling } from 'l-js-fn/polling';
const polling = new Polling();
polling.start(
async () => {
const response = await fetch('https://api.example.com/data');
return response.json();
},
1000,
true
);
polling.stop();
polling.running;
正则表达式 (regex)
import { REGEXP } from 'l-js-fn/regex';
REGEXP.PHONE.test('13800138000');
REGEXP.EMAIL.test('test@example.com');
REGEXP.URL.test('https://example.com');
REGEXP.ID_CARD.test('110101199001011234');
REGEXP.CHINESE.test('中文');
REGEXP.MONEY.test('123.45');
配置常量 (config)
import { DATE_FORMAT, HTTP_STATUS } from 'l-js-fn/config';
DATE_FORMAT.FULL;
DATE_FORMAT.DATE;
DATE_FORMAT.TIME;
HTTP_STATUS.OK;
HTTP_STATUS.UNAUTHORIZED;
HTTP_STATUS.NOT_FOUND;
IPC 通信 (ipc)
import { H5Bridge, IframeBridge } from 'l-js-fn/ipc';
const h5Bridge = new H5Bridge();
const iframeBridge = new IframeBridge('https://example.com');
编码/解码 (encode)
import {
base64Encode,
base64Decode,
escapeHTML,
unescapeHTML,
urlEncode,
urlDecode,
querystringify,
parseQueryString
} from 'l-js-fn/encode';
base64Encode('Hello World');
base64Encode('你好');
base64Decode('SGVsbG8gV29ybGQ=');
escapeHTML('<script>alert("XSS")</script>');
unescapeHTML('<div>');
urlEncode('Hello World!');
urlDecode('Hello%20World');
querystringify({ name: 'John', age: 20 });
querystringify({ a: [1, 2, 3] });
parseQueryString('name=John&age=20');
parseQueryString('?a=1&a=2');
文件处理 (file)
import {
formatFileSize,
getExtension,
getFileName,
downloadFile,
readAsText,
readAsDataURL,
readAsArrayBuffer,
isImage,
isVideo,
isAudio,
isPDF,
FileSizeUnit
} from 'l-js-fn/file';
formatFileSize(1024);
formatFileSize(1536000);
formatFileSize(1024, { precision: 0 });
formatFileSize(1000, { base: 1000 });
getExtension('image.png');
getExtension('/path/to/file.txt');
getFileName('/path/to/image.png');
getFileName('document.pdf');
const blob = new Blob(['Hello World'], { type: 'text/plain' });
downloadFile(blob, 'hello.txt');
const file = new File(['content'], 'test.txt');
await readAsText(file);
await readAsDataURL(file);
await readAsArrayBuffer(file);
isImage('photo.jpg');
isVideo('movie.mp4');
isAudio('music.mp3');
isPDF('document.pdf');
🌐 浏览器兼容性
- Chrome >= 90
- Firefox >= 88
- Safari >= 14
- Edge >= 90
📦 模块化导入
本项目支持多种导入方式:
import { isArray } from 'l-js-fn';
import { scrollTop } from 'l-js-fn/bom';
import { Polling } from 'l-js-fn/polling';
import { WebSocketManager } from 'l-js-fn/ws';
import { escapeHTML } from 'l-js-fn/encode';
import { formatFileSize } from 'l-js-fn/file';
const { isArray } = require('l-js-fn');
const { scrollTop } = require('l-js-fn/bom');
const { escapeHTML } = require('l-js-fn/encode');