在我的 Web 开发中有用的 JS 库

2025-06-04

在我的 Web 开发中有用的 JS 库

我在 Web 项目中使用了一些实用的 JS 库,有些很出名,有些应该也挺出名的。它们都不是面向框架的,你可以将它们与 React、Angular、Vue、JQuery 等一起使用。

lodash

lodash始终实用,它是一套用于处理字符串、可迭代对象、集合和函数的实用工具。无需另起炉灶,您总能在 lodash 中找到所需的一切。在 Web 应用中使用它时,需要注意两点。

  1. 别忘了只导入你需要的模块。你肯定不想在最终的打包文件中导入所有 lodash 工具。
  2. lodash/fp模块将使您能够以函数式编程风格使用它。
// import only the debounce function from lodash/fp
import debounce from 'lodash/fp/debounce'

const debounced = debounce(250)(search) // debounce the search function
Enter fullscreen mode Exit fullscreen mode

日期函数

与 lodash 类似,date-fns也拥有丰富的函数,但专注于处理日期。它是moment.js的绝佳替代方案。它使用原生 JavaScriptDate对象,您可以只导入所需的模块。格式化、解析、操作……大多数日期用例都可以用 date-fns 完成。

import formatRelative from 'date-fns/formatRelative'
import subDays from 'date-fns/subDays'

formatRelative(subDays(new Date(), 3), new Date())
//=> "last Friday at 7:26 p.m."
Enter fullscreen mode Exit fullscreen mode

Day.js也是 moment.js 的一个不错的替代品。它是一个极简的库(只有 2KB),但 API 几乎和 moment.js 一样完整。

验证器.js

在 Web 开发中,您始终需要验证用户的输入。validator.js包含您需要的所有验证功能:电子邮件、字母、货币、信用卡、MAC 地址等。超过 60 个验证器

import isEmail from 'validator/lib/isEmail'

isEmail('foo@bar.com') // true
Enter fullscreen mode Exit fullscreen mode

国际消息格式

intl-messageformat提供了一种管理应用字符串消息并将其格式化为本地化字符串的方法。它使用ICU 消息语法,适用于所有定义了复数规则的CLDR 语言。

import IntlMessageFormat from 'intl-messageformat';

const photos = `You have {numPhotos, plural,
    =0 {no photos.}
    =1 {one photo.}
    other {# photos.}
}`

const messages = new IntlMessageFormat(photos, 'en-US');

console.log(msg.format({numPhotos: 0}));    // => "You have no photos."
console.log(msg.format({numPhotos: 1}));    // => "You have one photo."
console.log(msg.format({numPhotos: 1000})); // => "You have 1,000 photos."
Enter fullscreen mode Exit fullscreen mode

DOMPurify

在某些 Web 应用中,我需要清理来自用户或外部来源的 HTML 字符串。我发现大多数库都很笨重。DOMPurify性能最强、速度最快的清理工具之一。它非常易于使用,你还可以覆盖其默认配置。

DOMPurify.sanitize('<img src=x onerror=alert(1)//>'); // becomes <img src="x">
DOMPurify.sanitize('<svg><g/onload=alert(2)//<p>'); // becomes <svg><g></g></svg>
DOMPurify.sanitize('<p>abc<iframe/\/src=jAva&Tab;script:alert(3)>def'); // becomes <p>abcdef</p>
DOMPurify.sanitize('<math><mi//xlink:href="data:x,<script>alert(4)</script>">'); // becomes <math><mi></mi></math>
DOMPurify.sanitize('<TABLE><tr><td>HELLO</tr></TABL>'); // becomes <table><tbody><tr><td>HELLO</td></tr></tbody></table>
Enter fullscreen mode Exit fullscreen mode

羽毛图标

羽毛图标是一组非常棒的精美开源图标。

羽毛图标

Faker.js

你厌倦了在单元测试和模型中使用乱码文字或foobar、 。所以,你应该看看faker.js。它可以生成地址、公司名称、账号、电话号码、图片等等。它支持多种语言和语言环境。这里有一个完整的演示baz

import faker from 'faker'

faker.name.findName() // Rowan Nikolaus
faker.internet.email() // Kassandra.Haley@erich.biz
faker.helpers.createCard() // random contact card containing many properties
Enter fullscreen mode Exit fullscreen mode

还有你。你在你的 Web 项目中使用哪个库?

文章来源:https://dev.to/bpetetot/useful-js-libs-in-my-web-developments-1l61
PREV
分治算法简介
NEXT
Docker 化 React 应用