关于javascript:几个常用js库别再重复造轮子了

50次阅读

共计 19598 个字符,预计需要花费 49 分钟才能阅读完成。

年底了,总结下往年用到的一些有意思的《js 轮子》(只是大略列出些比拟有意思的库,每个题目都是超链接,可点击自行查阅)
心愿能对您有用!

如有意思的 轮子 能够在评论列出一起探讨下


color

== 性能 ==:JavaScript 库,用于不可变的色彩转换和对 CSS 色彩字符串的反对。

npm install color
var color = Color('#7743CE').alpha(0.5).lighten(0.5);
console.log(color.hsl().string());  // 'hsla(262, 59%, 81%, 0.5)'
 
console.log(color.cmyk().round().array());  // [16, 25, 0, 8, 0.5]
 
console.log(color.ansi256().object());  // {ansi256: 183, alpha: 0.5}

uuidjs

== 性能 ==:UUID.js-JavaScript 的 RFC 兼容 UUID 生成器

// Create a version 4 (random number-based) UUID object
var objV4 = UUID.genV4();
 
// Create a version 1 (time-based) UUID object
var objV1 = UUID.genV1();
 
// Create a UUID object from a hexadecimal string
var uuid = UUID.parse("a0e0f130-8c21-11df-92d9-95795a3bcd40");
 
// Get string representations of a UUID object
console.log(uuid.toString());   // "a0e0f130-8c21-11df-92d9-95795a3bcd40"
console.log(uuid.hexString);    // "a0e0f130-8c21-11df-92d9-95795a3bcd40"
console.log(uuid.hexNoDelim);   // "a0e0f1308c2111df92d995795a3bcd40"
console.log(uuid.bitString);    // "101000001110000 ... 1100110101000000"
console.log(uuid.urn);          // "urn:uuid:a0e0f130-8c21-11df-92d9-95795a3bcd40"
 
// Compare UUID objects
console.log(objV4.equals(objV1));   // false
 
// Get UUID version numbers
console.log(objV4.version); // 4
console.log(objV1.version); // 1
 
// Get internal field values in 3 different forms via 2 different accessors
console.log(uuid.intFields.timeLow);                // 2699096368
console.log(uuid.bitFields.timeMid);                // "1000110000100001"
console.log(uuid.hexFields.timeHiAndVersion);       // "11df"
console.log(uuid.intFields.clockSeqHiAndReserved);  // 146
console.log(uuid.bitFields.clockSeqLow);            // "11011001"
console.log(uuid.hexFields.node);                   // "95795a3bcd40"
 
console.log(uuid.intFields[0]);                     // 2699096368
console.log(uuid.bitFields[1]);                     // "1000110000100001"
console.log(uuid.hexFields[2]);                     // "11df"
console.log(uuid.intFields[3]);                     // 146
console.log(uuid.bitFields[4]);                     // "11011001"
console.log(uuid.hexFields[5]);  

rc-upload

== 性能 ==:文件上传下载拖拽文件 及文件夹等

var Upload = require('rc-upload');
var React = require('react');
React.render(<Upload />, container);

react-copy-to-clipboard、clipboard

== 性能 ==:react 复制粘贴

npm install --save react react-copy-to-clipboard


import React from 'react';
import ReactDOM from 'react-dom';
import {CopyToClipboard} from 'react-copy-to-clipboard';
 
class App extends React.Component {
  state = {
    value: '',
    copied: false,
  };
 
  render() {
    return (
      <div>
        <input value={this.state.value}
          onChange={({target: {value}}) => this.setState({value, copied: false})} />
 
        <CopyToClipboard text={this.state.value}
          onCopy={() => this.setState({copied: true})}>
          <span>Copy to clipboard with span</span>
        </CopyToClipboard>
 
        <CopyToClipboard text={this.state.value}
          onCopy={() => this.setState({copied: true})}>
          <button>Copy to clipboard with button</button>
        </CopyToClipboard>
 
        {this.state.copied ? <span style={{color: 'red'}}>Copied.</span> : null}
      </div>
    );
  }
}
 
const appRoot = document.createElement('div');
document.body.appendChild(appRoot);
ReactDOM.render(<App />, appRoot);

numeral

== 性能 ==:一个用于格式化和解决数字的 javascript 库。


var value = myNumeral.value();
// 1000

var myNumeral2 = numeral('1,000');

var value2 = myNumeral2.value();
// 1000

omit.js

== 性能 ==:返回 在指标对象中 omit[删除; 疏忽] 指定属性的对象; 实用程序性能,用于创立删除了某些字段的对象的浅表正本。

npm i --save omit.js

omit(obj: Object, fields: string[]): Object


var omit = require('omit.js');
omit({name: 'Benjy', age: 18}, ['name']); // => {age: 18 

Moment.js

== 性能 ==:一个 JavaScript 日期库,用于解析,验证,操作和格式化日期。

moment().format('MMMM Do YYYY, h:mm:ss a'); // December 22nd 2020, 10:55:15 am
moment().format('dddd');                    // Tuesday
moment().format("MMM Do YY");               // Dec 22nd 20
moment().format('YYYY [escaped] YYYY');     // 2020 escaped 2020
moment().format();      

Day.js

== 性能 ==:Day.js 是一个轻量的解决工夫和日期的 JavaScript 库,和 Moment.js 的 API 设计放弃齐全一样. 如果您已经用过 Moment.js, 那么您曾经晓得如何应用 Day.js


dayjs().format('{YYYY} MM-DDTHH:mm:ss SSS [Z] A') // 展现

dayjs()
  .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<any> = () => {const [currentArticle, setCurrentArticle] = useState<{url: string, content: any}>({url: '', content:''});

  const [treeNavs, setTreeNavs] = useState<any[]>([])

  // 初始为开发文档
  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 (
    <>
      <Row className='articles'>
        <Col flex='200px' className="articles-list">
          <Affix offsetTop={24}>
            <Menu defaultSelectedKeys={['1']} onClick={menuOnClick} theme='light'>
              <Menu.Item key="1"> 开发文档 </Menu.Item>
              <Menu.Item key="2"> 应用文档 </Menu.Item>
            </Menu>
          </Affix>

        </Col>
        <Col flex='1' className='articles-content'>
          <div className='articles-content_wrpper'>
            <ReactMarkdown
              className="markdown-body"
              source={currentArticle.content}
              escapeHtml={false}
              renderers={{heading: HeadBlock}}
            />
          </div>
        </Col>
        <Col flex='200px' className="articles-menu">
          <Affix offsetTop={20} >
            <Anchor style={{width: 160}}>
              {treeNavs.map((item: any) => {if (item.children) {
                    return (<Link href={`#${item.nodeKey}`} title={item.value} key={item.nodeKey}>
                        {item.children.map((childItem: any) => (<Link href={`#${childItem.nodeKey}`} title={childItem.value} key={childItem.nodeKey} />
                          ))
                        }
                      </Link>
                    )
                  } else {
                    return (<Link href={`#${item.nodeKey}`} title={item.value} key={item.nodeKey} />
                    )
                  }
                })
              }
            </Anchor>
          </Affix>
        </Col>
      </Row>
    </>
  );
};

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(r));
 
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


<template>
    <datetime format="MM/DD/YYYY" width="300px" v-model="val"></datetime>
</template>
 
<script>
import datetime from 'vuejs-datetimepicker';
 
export default {components: { datetime}
};
</script> 

vue-meta-info

== 性能 ==:基于 Vue 2.0 的单页面 meta info 治理.

<template>
  ...
</template>
 
<script>
  export default {
    metaInfo: {
      title: 'My Example App', // set a title
      meta: [{                 // set meta
        name: 'keyWords',
        content: 'My Example App'
      }]
      link: [{                 // set link
        rel: 'asstes',
        href: 'https://assets-cdn.github.com/'
      }]
    }
  }
</script>

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


<template>
  <vue-slider v-model="value" />
</template>

<script>
import VueSlider from 'vue-slider-component'
import 'vue-slider-component/theme/antd.css'

export default {
  components: {VueSlider},
  data () {
    return {value: 0}
  }
}
</script>

CodeMirror

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

vue-codemirror

== 性能 ==:

 <codemirror
        ref="editQuerySQL"
        @ready="onCodemirrorReady"
        @input="onCodemirrorInput"
        v-model="query.sql"
        :options="cmOptions"
      ></codemirror>
      
      
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('<h2 class="title">Hello world</h2>');

$('h2.title').text('Hello there!');
$('h2').addClass('welcome');

$.html();
//=> <html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>

libxmljs

== 性能 ==:解析 xml

node-fetch、got node

== 性能 ==:node-ajax

ora node

== 性能 ==:优雅的终端旋转器

const ora = require('ora');
 
const spinner = ora('Loading unicorns').start();
 
setTimeout(() => {
    spinner.color = 'yellow';
    spinner.text = 'Loading rainbows';
}, 1000);

node-mkdirp、rimraf node

== 性能 ==:Like mkdir -p UNIX 命令 rm-rf . nodejs 新建创立文件

var mkdirp = require('mkdirp');
    
mkdirp('/tmp/foo/bar/baz', function (err) {if (err) console.error(err)
    else console.log('pow!')
});

shelljs

== 性能 ==:hellJS 是在 Node.js API 之上的 Unix shell 命令的可移植(Windows / Linux / OS X)实现。您能够应用它打消 shell 脚本对 Unix 的依赖,同时依然保留其相熟而弱小的命令。您还能够全局装置它,以便能够从 Node 我的项目内部运行它 - 辞别那些厌恶的 Bash 脚本!

var shell = require('shelljs');
 
if (!shell.which('git')) {shell.echo('Sorry, this script requires git');
  shell.exit(1);
}
 
// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');
 
// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
  shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
  shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');

shx

== 性能 ==:Shx 是一个包装 ShellJS Unix 命令的包装器,为 npm 包脚本中简略的类 Unix 跨平台命令提供了一个简略的解决方案

  • ShellJS: Good for writing long scripts, all in JS, running via NodeJS (e.g. node myScript.js).
  • shx: Good for writing one-off commands in npm package scripts (e.g. “clean”: “shx rm -rf out/”).
npm install shx --save-dev

package.json:
{
  "scripts": {"clean": "shx rm -rf build dist && shx echo Done"}
}

node-ssh

== 性能 ==:Node-SSH 是 ssh2 的一个十分轻量级的 Promise 包装器。

chalk

== 性能 ==:给终端嵌套您想要的款式。

const chalk = require('chalk');
const log = console.log;

// Combine styled and normal strings
log(chalk.blue('Hello') + 'World' + chalk.red('!'));

// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));

// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));

// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));

// Nest styles of the same type even (color, underline, background)
log(chalk.green(
    'I am a green line' +
    chalk.blue.underline.bold('with a blue substring') +
    'that becomes green again!'
));

Nzh

== 性能 ==:实用于须要转换阿拉伯数字与中文数字的场景。
特点如下:

  • 以字符串的形式转换,没有超大数及浮点数等问题 (请自行对原数据进行四舍五入等操作)
  • 反对迷信记数法字符串的转换
  • 反对口语化
  • 反对自定义转换 (不论是兆, 京还是厘都能够用)
  • 对超大数反对用争议教少的万万亿代替亿亿
  • 当然, 你还能够把中文数字再转回阿拉伯数字
npm install nzh --save
var Nzh = require("nzh");
var nzhcn = require("nzh/cn"); // 间接应用简体中文
var nzhhk = require("nzh/hk"); // 繁体中文
var nzhcn = Nzh.cn;                 // 应用简体中文,  另外有 Nzh.hk -- 繁体中文

nzhcn.encodeS(100111);              // 转中文小写 >> 十万零一百一十一
nzhcn.encodeB(100111);              // 转中文大写 >> 壹拾万零壹佰壹拾壹
nzhcn.encodeS("1.23456789e+21");    // 迷信记数法字符串 >> 十二万三千四百五十六万万七千八百九十万亿
nzhcn.toMoney("100111.11");         // 转中文金额 >> 人民币壹拾万零壹佰壹拾壹元壹角壹分 

decko

节流 防抖
https://blog.csdn.net/qq_2955…

== 性能 ==:三个最有用的装璜器的简洁实现:

  • @bind:this 在办法内使常量的值
  • @debounce:限度对办法的调用
  • @memoize:依据参数缓存返回值
npm i -S decko

p-queue

== 性能 ==:对限度速率的异步(或同步)操作很有用。例如,在与 REST API 交互时或在执行 CPU / 内存密集型工作时。

const {default: PQueue} = require('p-queue');
const got = require('got');

const queue = new PQueue({concurrency: 1});

(async () => {await queue.add(() => got('https://sindresorhus.com'));
    console.log('Done: sindresorhus.com');
})();

(async () => {await queue.add(() => got('https://avajs.dev'));
    console.log('Done: avajs.dev');
})();

(async () => {const task = await getUnicornTask();
    await queue.add(task);
    console.log('Done: Unicorn task');
})();

sleep

== 性能 ==:sleep

npm i sleep

var sleep = require('sleep');
function msleep(n) {Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, n);
}
function sleep(n) {msleep(n*1000);
}

delay

== 性能 ==:将承诺推延肯定的工夫

npm install delay
const delay = require('delay');

(async () => {bar();

    await delay(100);

    // Executed 100 milliseconds later
    baz();})();

better-scroll

== 性能 ==:BetterScroll 是一款重点解决挪动端(已反对 PC)各种滚动场景需要的插件。它的外围是借鉴的 iscroll 的实现,它的 API 设计根本兼容 iscroll,在 iscroll 的根底上又扩大了一些 feature 以及做了一些性能优化。

https://better-scroll.github.io/docs/zh-CN/guide/#betterscroll-%E6%98%AF%E4%BB%80%E4%B9%88

create-keyframe-animation

== 性能 ==:应用 JavaScrip 在浏览器中动静生成 CSS 关键帧动画(不保护了)

vconsole

== 性能 ==:一个轻量、可拓展、针对手机网页的前端开发者调试面板。

<script src="path/to/vconsole.min.js"></script>
<script>
  // 初始化
  var vConsole = new VConsole();
  console.log('Hello world');
</script>

正文完
 0