几个常用js库,别再重复造轮子了

.set(‘month’, 3)

.month() // 获取

dayjs().add(1, ‘year’) // 处理

dayjs().isBefore(dayjs()) // 查询

[](()[milliseconds](()


==~~~~功能==:用于将时间转换为毫秒。

var ms = require(‘milliseconds’);

ms.seconds(2); // 2000

ms.minutes(2); // 120000

ms.hours(2); // 7200000

ms.days(2); // 172800000

ms.weeks(2); // 1209600000

ms.months(2); // 5259600000

ms.years(2); // 63115200000

[](()[filesize](()


功能:filesize.js提供了一种简单的方法来从数字(浮点数或整数)或字符串中获取人类可读的文件大小字符串。

npm i filesize

filesize(500); // “500 B”

filesize(500, {bits: true}); // “4 Kb”

filesize(265318, {base: 10}); // “265.32 kB”

filesize(265318); // “259.1 KB”

filesize(265318, {round: 0}); // “259 KB”

filesize(265318, {output: “array”}); // [259.1, “KB”]

filesize(265318, {output: “object”}); // {value: 259.1, symbol: “KB”, exponent: 1}

filesize(1, {symbols: {B: “Б”}}); // “1 Б”

filesize(1024); // “1 KB”

filesize(1024, {exponent: 0}); // “1024 B”

filesize(1024, {output: “exponent”}); // 1

filesize(265318, {standard: “iec”}); // “259.1 KiB”

filesize(265318, {standard: “iec”, fullform: true}); // “259.1 kibibytes”

filesize(12, {fullform: true, fullforms: [“байтов”]}); // “12 байтов”

filesize(265318, {separator: “,”}); // “259,1 KB”

filesize(265318, {locale: “de”}); // “259,1 KB”

[](()[react-markdown](()


功能:使用备注的React的Markdown组件。

import { Row, Col, Menu, Affix, Anchor } from ‘antd’;

import ReactMarkdown from ‘react-markdown/with-html’;

import { isEmpty } from “lodash”;

import HeadBlock from ‘./HeadBlock’;

import ‘github-markdown-css/github-markdown.css’

import ‘./index.less’;

const { Link } = Anchor;

const articles = {

‘1’: ‘/developer_guide.md’,

‘2’: ‘/user_manual.md’

}

/**

  • @param lists

  • 这里只做两级处理

*/

export const navsToTree = (lists: any[]) => {

if (isEmpty(lists)) return [];

// 提取第一个level为最大level 后续比他大的一律为同级

const maxLevel = lists[0].level;

const newLists: any[] = [];

lists.forEach((item: any) => {

// 一级 同级

if (item.level <= maxLevel) {

newLists.push(item)

} else {

// 非同级

if (newLists[newLists.length - 1].children) {

newLists[newLists.length - 1].children.push(item)

} else {

newLists[newLists.length - 1].children = [item]

}

}

})

return newLists;

}

const NormalTest: React.FC = () => {

const [currentArticle, setCurrentArticle] = useState<{ url: string, content: any }>({ url: ‘’, content: ‘’ });

const [treeNavs, setTreeNavs] = useState([])

// 初始为开发文档

useEffect(() => {

// console.log(1);

changeCurrentArticle(articles[‘1’])

}, [])

// 这里是根据文档修改进行获取目录

useEffect(() => {

/**

  • 获取所有的文章标题

*/

// console.log(currentArticle);

const markdownNavs = document.querySelectorAll(‘.article-nav’)

const navs: any[] = [];

markdownNavs.forEach((item: any) => {

const level = item.getAttribute(‘data-level’);

const value = item.textContent;

const nodeKey = item.id;

navs.push({ level, value, nodeKey })

})

transArticleNavs(navs)

}, [currentArticle.content])

// 更改当前文档

const changeCurrentArticle = async (url: string) => {

const res = await fetch(url);

const content = await res.text();

setCurrentArticle({ …currentArticle, content, url })

}

// 书籍导航点击

const menuOnClick = (e: any) => {

const url = articles[e.key]

changeCurrentArticle(url)

}

// 转换为文章右侧目录

const transArticleNavs = (navs: any) => {

// 转换为二级导航

const treedevelopDocs = navsToTree(navs);

setTreeNavs(treedevelopDocs)

}

return (

<>

开发文档

使用文档

className=“markdown-body”

source={currentArticle.content}

escapeHtml={false}

renderers={{

heading: HeadBlock

}}

/>

{

treeNavs.map((item: any) => {

if (item.children) {

return (

{

item.children.map((childItem: any) => (

))

}

)

} else {

return (

)

}

})

}

);

};

export default NormalTest;

import React from ‘react’;

const HeadBlock = (props) => {

const { level, children } = props;

const { nodeKey } = children[0].props;

return (

<>

{React.createElement(h${level}, { className: ‘article-nav’, id: nodeKey, ‘data-level’: level }, children)}

);

}

export default HeadBlock;

[](()[cytoscape](() | cytoscape-dagre


功能:Cytoscape.js是功能齐全的图论库。您是否需要对关系数据进行建模和/或可视化,例如生物数据或社交网络?如果是这样,Cytoscape.js就是您所需要的。Cytoscape.js包含一个图形理论模型和一个用于显示交互式图形的可选渲染器。该库旨在使程序员和科学家尽可能轻松地在其应用程序中使用图论,无论是用于Node.js应用程序中的服务器端分析还是用于丰富的用户界面。

[](()[Lodash](()


功能:函数工具类库

// Load the full build.

var _ = require(‘lodash’);

// Load the core build.

var _ = require(‘lodash/core’);

// Load the FP build for immutable auto-curried iteratee-first data-last methods.

var fp = require(‘lodash/fp’);

// Load method categories.

var array = require(‘lodash/array’);

var object = require(‘lodash/fp/object’);

// Cherry-pick methods for smaller browserify/rollup/webpack bundles.

var at = require(‘lodash/at’);

var curryN = require(‘lodash/fp/curryN’);

[](()[patch-package](() node


功能:npm yran 补丁,用于改node_modules

[](()[cross-env](() node


功能:

cross-env这是一款运行跨平台设置和使用环境变量的脚本。

npm install --save-dev cross-env

{

“scripts”: {

“parentScript”: “cross-env GREET=“Joe” npm run childScript”,

“childScript”: “cross-env-shell “echo Hello $GREET””

}

}

[](()[bignumber.js](()


功能:一个用于任意精度十进制和非十进制算术的JavaScript库

https://mikemcl.github.io/bignumber.js/

https://juejin.cn/post/6844903704714280968#heading-7

[](()[QRCode.js](()、 [qrcode.vue](()


功能:

npm install --save qrcode.vue

npm i qrcodejs2

getBlob(base64) {

const mimeString = base64.split(‘,’)[0].split(‘:’)[1].split(‘;’)[0]; // mime类型

const byteString = atob(base64.split(‘,’)[1]); // base64 解码

const arrayBuffer = new ArrayBuffer(byteString.length); // 创建缓冲数组

const intArray = new Uint8Array(arrayBuffer); // 创建视图

for (let i = 0; i < byteString.length; i += 1) {

intArray[i] = byteString.charCodeAt(i);

}

return new Blob([intArray], {

type: mimeString,

});

},

savePicture(Url = this.qrcodeUrl) {

const blob = new Blob([‘’], { type: ‘application/octet-stream’ });

const url = URL.createObjectURL(blob);

const a = document.createElement(‘a’);

a.href = Url;

// eslint-disable-next-line prefer-destructuring

a.download = Url.replace(/(./)([^.]+.*)/gi, ‘$2’).split(‘?’)[0];

const e = document.createEvent(‘MouseEvents’);

e.initMouseEvent(

‘click’,

true,

false,

window,

0,

0,

0,

0,

0,

false,

false,

false,

false,

0,

null,

);

a.dispatchEvent(e);

URL.revokeObjectURL(url);

},

_qrcode(url) {

const div = document.createElement(‘div’);

// eslint-disable-next-line new-cap

const code = new QRCode(div, {

text: url,

width: 500,

height: 500,

colorDark: ‘#000000’,

colorLight: ‘#ffffff’,

correctLevel: QRCode.CorrectLevel.L,

});

// 这里如果需要在页面上展示的话,就将div节点给添加到dom树上去;node.appendChild(div)

const canvas = code._el.querySelector(‘canvas’); // 获取生成二维码中的canvas,并将canvas转换成base64

const base64Text = canvas.toDataURL(‘image/png’);

const blob = this.getBlob(base64Text); // 将base64转换成blob对象

return window.URL.createObjectURL(blob);

},

[](()[cssnano](()、[js-beautify](()


功能: css js 压缩工具

[](()[cors](() node


功能:CORS是一个node.js软件包,用于提供可用于通过各种选项启用CORS的Connect / Express中间件。

npm install cors

var cors = require(‘cors’);

app.use(

cors({

origin: [‘http://localhost:8000’],

methods: [‘GET’, ‘POST’],

alloweHeaders: [‘Conten-Type’, ‘Authorization’],

})

);

[](()[countup.js](()


功能:数字滚动插件使用方法详解

npm i countup.js

interface CountUpOptions {

startVal?: number; // number to start at (0)

decimalPlaces?: number; // number of decimal places (0)

duration?: number; // animation duration in seconds (2)

useGrouping?: boolean; // example: 1,000 vs 1000 (true)

useEasing?: boolean; // ease animation (true)

smartEasingThreshold?: number; // smooth easing for large numbers above this if useEasing (999)

smartEasingAmount?: number; // amount to be eased for numbers above threshold (333)

separator?: string; // grouping separator (‘,’)

decimal?: string; // decimal (‘.’)

// easingFn: easing function for animation (easeOutExpo)

easingFn?: (t: number, b: number, c: number, d: number) => number;

formattingFn?: (n: number) => string; // this function formats result

prefix?: string; // text prepended to result

suffix?: string; // text appended to result

numerals?: string[]; // numeral glyph substitution

}

[](()[js-base64](()


功能:另一个Base64转码器。

npm install --save js-base64

require=require(‘esm’)(module);

import {Base64} from ‘js-base64’;

let latin = ‘dankogai’;

let utf8 = ‘小飼弾’

let u8s = new Uint8Array([100,97,110,107,111,103,97,105]);

Base64.encode(latin); // ZGFua29nYWk=

Base64.btoa(latin); // ZGFua29nYWk=

Base64.btoa(utf8); // raises exception

Base64.fromUint8Array(u8s); // ZGFua29nYWk=

Base64.fromUint8Array(u8s, true); // ZGFua29nYW which is URI safe

Base64.encode(utf8); // 5bCP6aO85by+

Base64.encode(utf8, true) // 5bCP6aO85by-

Base64.encodeURI(utf8); // 5bCP6aO85by-

[](()[json-bigint](()


功能: Native Bigint是最近添加到JS的,因此我们添加了一个利用它的选项,而不是bignumber.js。但是,使用本机BigInt进行解析仍然是向后兼容的选项。

var JSONbig = require(‘json-bigint’);

var json = ‘{ “value” : 9223372036854775807, “v2”: 123 }’;

console.log(‘Input:’, json);

console.log(‘’);

console.log(‘node.js built-in JSON:’);

var r = JSON.parse(json);

console.log('JSON.parse(input).value : ', r.value.toString());

console.log(‘JSON.stringify(JSON.parse(input)):’, JSON.stringify®);

console.log(‘\n\nbig number JSON:’);

var r1 = JSONbig.parse(json);

console.log('JSONbig.parse(input).value : ', r1.value.toString());

console.log(‘JSONbig.stringify(JSONbig.parse(input)):’, JSONbig.stringify(r1));

[](()[vuejs-datetimepicker](()


功能:

npm install vuejs-datetimepicker

[](()[vue-meta-info](()


功能:基于Vue 2.0 的单页面 meta info 管理.

[](()[vue-smooth-scroll](()


功能:Scroll

npm install --save vue-smooth-scroll

import vueSmoothScroll from ‘vue-smooth-scroll’

Vue.use(vueSmoothScroll)

[](()[prismjs](()


功能:Prism是一个轻量,健壮,优雅的语法高亮库。这是Dabblet的衍生项目。

[](()[vuex-persistedstate](()


功能:

npm install --save vuex-persistedstate

import createPersistedState from ‘vuex-persistedstate’;

import * as Cookies from ‘js-cookie’;

import cookie from ‘cookie’;

export default ({ store, req }) => {

createPersistedState({

paths: […],

storage: {

getItem: (key) => {

// See https://nuxtjs.org/guide/plugins/#using-process-flags

if (process.server) {

const parsedCookies = cookie.parse(req.headers.cookie);

return parsedCookies[key];

} else {

return Cookies.get(key);

}

},

// Please see https://github.com/js-cookie/js-cookie#json, on how to handle JSON.

setItem: (key, value) =>

Cookies.set(key, value, { expires: 365, secure: false }),

removeItem: key => Cookies.remove(key)

}

})(store);

};

[](()[vue-slider-component](()


功能:一个高度定制化的滑块组件

$ yarn add vue-slider-component

npm install vue-slider-component --save

[](()[CodeMirror](()


功能:CodeMirror是使用JavaScript为浏览器实现的多功能文本编辑器。它专门用于编辑代码,并具有100多种语言模式和各种插件,可实现更高级的编辑功能。每种语言都带有功能齐全的代码和语法高亮显示,以帮助阅读和编辑复杂代码。

[](()[vue-codemirror](()


功能:

ref=“editQuerySQL”

@ready=“onCodemirrorReady”

@input=“onCodemirrorInput”

v-model=“query.sql”

:options=“cmOptions”

import { codemirror } from ‘vue-codemirror’;

import { getEthdb } from ‘@/api’;

import ‘codemirror/lib/codemirror.css’;

import ‘codemirror/theme/idea.css’;

// import ‘codemirror/theme/base16-dark.css’;

import ‘codemirror/theme/panda-syntax.css’;

import ‘codemirror/addon/hint/show-hint.css’;

import ‘codemirror/lib/codemirror’;

import ‘codemirror/mode/sql/sql’;

import ‘codemirror/addon/hint/show-hint’;

import ‘codemirror/addon/hint/sql-hint’;

export default {

data(){

retrun {

query: {

sql: ‘SELECT * FROM ethblock LIMIT 200’,

},

cmOptions: {

scroll: false,

tabSize: 4,

lineNumbers: false,

line: false,

indentWithTabs: true,

smartIndent: true,

autofocus: false,

mode: ‘text/x-mariadb’,

theme: ‘idea’,

hintOptions: {

completeSingle: false,

},

},

}

},

methods:{

onCodemirrorReady(cm) {

cm.on(‘keypress’, () => {

cm.showHint();

});

},

onCodemirrorInput(newQuery) {

this.query.sql = newQuery;

},

}

}

[](()[portfinder](() || [get-port](() node


功能:端口查看器

[sudo] npm install portfinder

portfinder.getPort({

port: 3000, // minimum port

stopPort: 3333 // maximum port

}, callback);

[](()[regedit](() node


功能:使用node.js和Windows脚本宿主对Windows注册表进行读取,写入,列出和处理各种时髦的事情。

[](()[lowdb](()


功能:适用于Node,Electron和浏览器的小型JSON数据库。由Lodash驱动。 ⚡️

npm install lowdb

const low = require(‘lowdb’)

const FileSync = require(‘lowdb/adapters/FileSync’)

const adapter = new FileSync(‘db.json’)

const db = low(adapter)

// Set some defaults

db.defaults({ posts: [], user: {} })

.write()

// Add a post

db.get(‘posts’)

.push({ id: 1, title: ‘lowdb is awesome’})

.write()

// Set a user using Lodash shorthand syntax

db.set(‘user.name’, ‘typicode’)

.write()

[](()[cheerio](() node


功能:为服务器特别定制的,快速、灵活、实施的jQuery核心实现. 爬虫

npm install cheerio

const cheerio = require(‘cheerio’);

const $ = cheerio.load(‘

Hello world

’);

你可能感兴趣的:(Web前端,经验分享,前端,前端框架)