可以但没必要?分享 20 个 JavaScript 库,打开视野👀

17,363 阅读5分钟

小知识,大挑战!本文正在参与「程序员必备小知识」创作活动

本文已参与 「掘力星计划」 ,赢取创作大礼包,挑战创作激励金。

小感:近来诸君或多见 List 文,所谓 List 文者,形如 10 个、20 个推荐尔尔,更有甚者,万字分点罗列,吸睛之极,诚流量密码;本瓜评 List 文,不愿论其褒贬,因其根本不过是行文之形式也,好坏与否,评判标准在其内容;诸君阅文,多有匆匆一瞥,List 文,涵盖广、脉络清、门槛低、目的明、各所需,何乐不为?但特告诫笔者,勿毁其优势,填充多以糟糠,使众看客见标题便恶之、远之,本末倒置也。🐶

1. Immutable.js

如今 React+Redux+Immutable.js 的组合已在项目中广泛应用,但对于 Vue 技术栈的同学们来说,认知 immutable-js 也同样关键且必要。

通过 immutable-js 构造的数据一旦创建,就不会更改;原理是:每当对其进行修改时,会返回一个新的 immutable 对象,以此来保证先前数据不可变(底层数据结构 Trie 前缀树 + 结构共享 Structural Sharin)。

687474703a2f2f696d672e616c6963646e2e636f6d2f7470732f69322f5442317a7a695f4b5858585858637458465858627262384f5658582d3631332d3537352e676966.gif

如果对象树中一个节点发生变化,只修改这个节点和受它影响的父节点,其它节点则进行共享

这样做的优势就是:节省 CPU、节省内存;

因为我们常通过深拷贝解决不变数据的问题,深拷贝即需要做额外的操作消耗 CPU、拷贝新数据需新内存;

例🌰

import { Map} from 'immutable';
let a = Map({
  select: 'users',
  filter: Map({ name: 'Cam' })
})
let b = a.set('select', 'people');

a === b; // false
a.get('filter') === b.get('filter'); // true

2. Redux.js

Redux 并非 React 人专用,它借用函数式编程思想,旨在提供可预测的状态管理;

具体的,在 Redux 中的 state 没有 setter 方法,取而代之的是:state 经过一个接一个的 reducer 函数计算后得值,state 只读,不可修改;

这正是 FP 中 把原始不可变的数据放入不同函数组合成的管道进行计算 的思想!

例🌰

function visibilityFilter(state = 'SHOW_ALL', action) { // state 只读
  switch (action.type) {
    case 'SET_VISIBILITY_FILTER':
      return action.filter
    default:
      return state
  }
}

function todos(state = [], action) {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        {
          text: action.text,
          completed: false
        }
      ]
    case 'COMPLETE_TODO':
      return state.map((todo, index) => {
        if (index === action.index) {
          return Object.assign({}, todo, {
            completed: true
          })
        }
        return todo
      })
    default:
      return state
  }
}

import { combineReducers, createStore } from 'redux'
let reducer = combineReducers({ visibilityFilter, todos }) // Reducer 组合 == 函数组合
let store = createStore(reducer)

3. Omniscient.js

Omniscient.js 用于将 不可变数据 自上而下的快速渲染;

image.png

例🌰

var React = require('react');
var ReactDOM = require('react-dom');
var component = require('omniscient');

var HelloMessage = component(({name}) => <div>Hello {name}</div>);

ReactDOM.render(<HelloMessage name="John" />, document.querySelector('#app'));

// without JSX

var {div} = React.DOM; // Extract the div convenience function from React

var HelloMessage = component(({name}) => div({}, `Hello ${name}`));
// Omniscient components are interoperable with JSX and non-JSX
ReactDOM.render(HelloMessage({ name: 'John' }), document.querySelector('#app'));

4. D3.js

至于 JavaScript 可视化图表库,本瓜一直用 Echart.js,永远的神;

image.png

不过,要知道的是 Github 上 star 最多的 JS 图标库是 D3.js Star 98.8K+ ✨

image.png

Chart.js Star 55K+ ✨ 次之;

5. SurveyJS

SurveyJS 是目前可用的最多的 feature-rich 调查/表单库;并且它可以很容易地定制和扩展,以满足您的需要。

image.png

配置后生成代码:

43c72fc7-2d47-494e-9b8d-84c71dc03de5.gif

6. Final Form

轻松创建漂亮且易于表单的库;

image.png

当表单状态更改时,React Final Form 能重新渲染仅需要更新的组件:

import { Form, Field } from 'react-final-form'
const MyForm = () => (
  <Form
    onSubmit={onSubmit}
    validate={validate}
    render={({ handleSubmit }) => (
      <form onSubmit={handleSubmit}>
        <h2>Simple Default Input</h2>
        <div>
          <label>First Name</label>
          <Field name="firstName" component="input" placeholder="First Name" />
        </div>

        <h2>An Arbitrary Reusable Input Component</h2>
        <div>
          <label>Interests</label>
          <Field name="interests" component={InterestPicker} />
        </div>

        <h2>Render Function</h2>
        <Field
          name="bio"
          render={({ input, meta }) => (
            <div>
              <label>Bio</label>
              <textarea {...input} />
              {meta.touched && meta.error && <span>{meta.error}</span>}
            </div>
          )}
        />

        <h2>Render Function as Children</h2>
        <Field name="phone">
          {({ input, meta }) => (
            <div>
              <label>Phone</label>
              <input type="text" {...input} placeholder="Phone" />
              {meta.touched && meta.error && <span>{meta.error}</span>}
            </div>
          )}
        </Field>

        <button type="submit">Submit</button>
      </form>
    )}
  />
)

7. Choreographer.js

一个简单的库来处理复杂的动画;

$ npm install --save choreographer-js
const Choreographer = require('choreographer-js')

let choreographer = new Choreographer({
  animations: [
    {
      range: [-1, 1000],
      selector: '#box',
      type: 'scale',
      style: 'opacity',
      from: 0,
      to: 1
    }
  ]
})

window.addEventListener('mousemove', function(e) {
    choreographer.runAnimationsAt(e.clientX)
})

Choreographer-JS-_-Example-Two-Google-Chrome-2021-10-09-16-26-4420211091628141.gif

8. typeahead.js

在输入框输入信息后,自动提示补全;

image.png

9. Multiple.js

创建跨多个元素的共享背景(包括背景的渐变效果),激发网站视觉;

image.png

.selector {
  background-image: linear-gradient(white, black);
  background-size: cover;
  background-position: center;
  background-attachment: fixed;  /* <- here it is */

  width: 100px;
  height: 100px;
}

关键:background-attachment: fixed 将背景扩展到视口的大小并在每个元素中显示适当的块;不过在移动端,则需 clip: rect(0 auto auto 0) 额外处理;

10. ApexCharts

图表具有更好的交互~~ 适用 js 原生 + 3 大框架;

image.png

本瓜体验了一下,确实有不一样的交互感受,很细节(●'◡'●);

11. Premonish.js

Premonish 可以检测用户鼠标的移动位置并预测他们要移向哪个元素,帅的嘛,不谈了~~ 😀

image.png

前往体验便知它是怎么预测的:地址

import Premonish from 'premonish';
const premonish = new Premonish({
  selectors: ['a', '.list-of' '.selectors', '.to', '#watch'],
  elements: [] // Alternatively, provide a list of DOM elements to watch
});

premonish.onIntent(({el, confidence}) => {
  console.log(el); // The DOM node we suspect the user is about to interact with.
  console.log(confidence); // How confident are we about the user's intention? Scale 0-1
});

12. Stretchy

用于表单元素自动调整大小;还能监听你的 input 等文本框大小,如果尺寸错误,则会报错;体积 1.5KB;

image.png

13. Hammer.JS

Hammer 是一个开源库,可以识别由触摸、鼠标和指针事件做出的手势。它没有任何依赖关系,而且很小,只有 7.34 kB!

image.png

var hammertime = new Hammer(myElement, myOptions);
hammertime.on('pan', function(ev) {
	console.log(ev);
});

默认情况下,它添加了一组tapdoubletappress水平 panswipe以及多点触控pinchrotate识别器;

14. JS Encrypt

JS Encrypt 为应用程序提供易于实现的 RSA JavaScript 加密;

image.png

Demo 地址

15. Discord.js

discord.js 是一个强大的 Node.js 模块,可让您轻松与 Discord API 交互;

  • Discord 是一款专为社群设计的免费网路即时通话软体与数位发行平台,拥有 1.3 亿注册用户;

image.png

16. Google Maps Utility Library

顾名思义,谷歌地图共用库,可将 Google 地图导航,以及其它基于地图的功能应用于你的程序当中;

image.png

17. Typed.js

Typed.js 提供打字动画,兼容性极好。

Typed.js-Type-your-heart-out-Google-Chrome-2021-10-10-13-17-5220211010131981.gif

18. Math.js

有了这个库,复杂的数学问题就可以在前端浏览器上计算,而不会给后端服务器带来压力;它具有灵活的表达式解析器,支持符号计算,内置大量函数和常量,并提供了一个集成的解决方案来处理不同的数据类型,如数字、大数、复数、分数、单位和矩阵;

功能强大且易于使用~

image.png

19. howler.js

howler.js 让音频处理变得容易、好用;

image.png

image.png

20. ScrollMagic

给你得网页滚动效果施加魔法!

ScrollMagic-♥-Demo-Google-Chrome-2021-10-10-13-33-12202110101334313.gif

image.png

纸上得来终觉浅,抽空也试一试吧~~

小结

可以看到,以上分享的库,有的库高达几百 K star,有的库在小 1 K star 徘徊,但也丝毫不影响它们被列在一起;本瓜以为:反而,这些体量小的库,能针对解决某一项问题,核心原理奇妙,官网也做得特别精美,叫人爱之尤甚;

还是那句老话:工具选的好,下班下的早;开发工作分两类:写轮子的为一类,用轮子的为一类;写轮子也是从用轮子做起的,因为找不到更适用的轮子,才想自己写一个,分享给大家用;开源万岁!

以上。愿君有所获~

我是掘金安东尼,公众号同名,输出暴露输入,技术洞见生活,再会!