当前位置:   article > 正文

50 个常用的 JS 工具库,让你避免重复造轮子

js工具库

0c1432bdd048db609f7b7b3af3f95b2e.png

总结下今年用到的一些有意思的《js轮子》(只是大概列出些比较有意思的库,每个标题下都是超链接,可点击自行查阅) 希望能对您有用!如有意思的 轮子 可以在评论列出一起讨论下


color

https://www.npmjs.com/package/color

==功能==:JavaScript库,用于不可变的颜色转换和对CSS颜色字符串的支持。

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

uuidjs

https://www.npmjs.com/package/uuidj

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

  1. // Create a version 4 (random number-based) UUID object
  2. var objV4 = UUID.genV4();
  3.  
  4. // Create a version 1 (time-based) UUID object
  5. var objV1 = UUID.genV1();
  6.  
  7. // Create a UUID object from a hexadecimal string
  8. var uuid = UUID.parse("a0e0f130-8c21-11df-92d9-95795a3bcd40");
  9.  
  10. // Get string representations of a UUID object
  11. console.log(uuid.toString());   // "a0e0f130-8c21-11df-92d9-95795a3bcd40"
  12. console.log(uuid.hexString);    // "a0e0f130-8c21-11df-92d9-95795a3bcd40"
  13. console.log(uuid.hexNoDelim);   // "a0e0f1308c2111df92d995795a3bcd40"
  14. console.log(uuid.bitString);    // "101000001110000 ... 1100110101000000"
  15. console.log(uuid.urn);          // "urn:uuid:a0e0f130-8c21-11df-92d9-95795a3bcd40"
  16.  
  17. // Compare UUID objects
  18. console.log(objV4.equals(objV1));   // false
  19.  
  20. // Get UUID version numbers
  21. console.log(objV4.version); // 4
  22. console.log(objV1.version); // 1
  23.  
  24. // Get internal field values in 3 different forms via 2 different accessors
  25. console.log(uuid.intFields.timeLow);                // 2699096368
  26. console.log(uuid.bitFields.timeMid);                // "1000110000100001"
  27. console.log(uuid.hexFields.timeHiAndVersion);       // "11df"
  28. console.log(uuid.intFields.clockSeqHiAndReserved);  // 146
  29. console.log(uuid.bitFields.clockSeqLow);            // "11011001"
  30. console.log(uuid.hexFields.node);                   // "95795a3bcd40"
  31.  
  32. console.log(uuid.intFields[0]);                     // 2699096368
  33. console.log(uuid.bitFields[1]);                     // "1000110000100001"
  34. console.log(uuid.hexFields[2]);                     // "11df"
  35. console.log(uuid.intFields[3]);                     // 146
  36. console.log(uuid.bitFields[4]);                     // "11011001"
  37. console.log(uuid.hexFields[5]);

rc-upload

https://www.npmjs.com/package/rc-upload

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

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

react-copy-to-clipboard

https://www.npmjs.com/package/react-copy-to-clipboard

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

  1. npm install --save react react-copy-to-clipboard
  2. import React from 'react';
  3. import ReactDOM from 'react-dom';
  4. import {CopyToClipboard} from 'react-copy-to-clipboard';
  5.  
  6. class App extends React.Component {
  7.   state = {
  8.     value: '',
  9.     copied: false,
  10.   };
  11.  
  12.   render() {
  13.     return (
  14.       <div>
  15.         <input value={this.state.value}
  16.           onChange={({target: {value}}) => this.setState({value, copied: false})} />
  17.  
  18.         <CopyToClipboard text={this.state.value}
  19.           onCopy={() => this.setState({copied: true})}>
  20.           <span>Copy to clipboard with span</span>
  21.         </CopyToClipboard>
  22.  
  23.         <CopyToClipboard text={this.state.value}
  24.           onCopy={() => this.setState({copied: true})}>
  25.           <button>Copy to clipboard with button</button>
  26.         </CopyToClipboard>
  27.  
  28.         {this.state.copied ? <span style={{color: 'red'}}>Copied.</span> : null}
  29.       </div>
  30.     );
  31.   }
  32. }
  33.  
  34. const appRoot = document.createElement('div');
  35. document.body.appendChild(appRoot);
  36. ReactDOM.render(<App />, appRoot);

numeral

http://numeraljs.com/

==功能==:一个用于格式化和处理数字的javascript库。

  1. var value = myNumeral.value();
  2. // 1000
  3. var myNumeral2 = numeral('1,000');
  4. var value2 = myNumeral2.value();
  5. // 1000

omit.js

https://www.npmjs.com/package/omit.js

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

  1. npm i --save omit.js
  2. omit(obj: Object, fields: string[]): Object
  3. var omit = require('omit.js');
  4. omit({ name: 'Benjy', age: 18 }, [ 'name' ]); // => { age: 18

Moment.js

https://momentjs.com/

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

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

Day.js

https://github.com/iamkun/dayjs/blob/HEAD/docs/zh-cn/README.zh-CN.md

==功能==:Day.js 是一个轻量的处理时间和日期的 JavaScript 库,和 Moment.js 的 API 设计保持完全一样. 如果您曾经用过 Moment.js, 那么您已经知道如何使用 Day.js

  1. dayjs().format('{YYYY} MM-DDTHH:mm:ss SSS [Z] A'// 展示
  2. dayjs()
  3.   .set('month'3)
  4.   .month() // 获取
  5. dayjs().add(1'year'// 处理
  6. dayjs().isBefore(dayjs()) // 查询

milliseconds

https://github.com/HenrikJoreteg/milliseconds

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

  1. var ms = require('milliseconds');
  2. ms.seconds(2); // 2000
  3. ms.minutes(2); // 120000
  4. ms.hours(2);   // 7200000
  5. ms.days(2);    // 172800000
  6. ms.weeks(2);   // 1209600000
  7. ms.months(2);  // 5259600000
  8. ms.years(2);   // 63115200000

filesize

https://www.npmjs.com/package/filesize

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

  1. npm i filesize
  2. filesize(500);                        // "500 B"
  3. filesize(500, {bits: true});          // "4 Kb"
  4. filesize(265318, {base: 10});         // "265.32 kB"
  5. filesize(265318);                     // "259.1 KB"
  6. filesize(265318, {round: 0});         // "259 KB"
  7. filesize(265318, {output: "array"});  // [259.1, "KB"]
  8. filesize(265318, {output: "object"}); // {value: 259.1, symbol: "KB", exponent: 1}
  9. filesize(1, {symbols: {B: "Б"}});     // "1 Б"
  10. filesize(1024);                       // "1 KB"
  11. filesize(1024, {exponent: 0});        // "1024 B"
  12. filesize(1024, {output: "exponent"}); // 1
  13. filesize(265318, {standard: "iec"});  // "259.1 KiB"
  14. filesize(265318, {standard: "iec", fullform: true}); // "259.1 kibibytes"
  15. filesize(12, {fullform: true, fullforms: ["байтов"]});  // "12 байтов"
  16. filesize(265318, {separator: ","});   // "259,1 KB"
  17. filesize(265318, {locale: "de"});   // "259,1 KB"

react-markdown

https://www.npmjs.com/package/react-markdown

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

  1. import { Row, Col, Menu, Affix, Anchor } from 'antd';
  2. import ReactMarkdown from 'react-markdown/with-html';
  3. import { isEmpty } from "lodash";
  4. import HeadBlock from './HeadBlock';
  5. import 'github-markdown-css/github-markdown.css'
  6. import './index.less';
  7. const { Link } = Anchor;
  8. const articles = {
  9.   '1''/developer_guide.md',
  10.   '2''/user_manual.md'
  11. }
  12. /**
  13.  *
  14.  * @param lists
  15.  * 这里只做两级处理
  16.  */
  17. export const navsToTree = (lists: any[]) => {
  18.   if (isEmpty(lists)) return [];
  19.   // 提取第一个level为最大level 后续比他大的一律为同级
  20.   const maxLevel = lists[0].level;
  21.   const newLists: any[] = [];
  22.   lists.forEach((item: any) => {
  23.     // 一级 同级
  24.     if (item.level <= maxLevel) {
  25.       newLists.push(item)
  26.     } else {
  27.       // 非同级
  28.       if (newLists[newLists.length - 1].children) {
  29.         newLists[newLists.length - 1].children.push(item)
  30.       } else {
  31.         newLists[newLists.length - 1].children = [item]
  32.       }
  33.     }
  34.   })
  35.   return newLists;
  36. }
  37. const NormalTest: React.FC<any> = () => {
  38.   const [currentArticle, setCurrentArticle] = useState<{ url: string, content: any }>({ url: '', content: '' });
  39.   const [treeNavs, setTreeNavs] = useState<any[]>([])
  40.   // 初始为开发文档
  41.   useEffect(() => {
  42.     // console.log(1);
  43.     changeCurrentArticle(articles['1'])
  44.   }, [])
  45.   // 这里是根据文档修改进行获取目录
  46.   useEffect(() => {
  47.     /**
  48.      *  获取所有的文章标题
  49.      */
  50.       // console.log(currentArticle);
  51.     const markdownNavs = document.querySelectorAll('.article-nav')
  52.     const navs: any[] = [];
  53.     markdownNavs.forEach((item: any) => {
  54.       const level = item.getAttribute('data-level');
  55.       const value = item.textContent;
  56.       const nodeKey = item.id;
  57.       navs.push({ level, value, nodeKey })
  58.     })
  59.     transArticleNavs(navs)
  60.   }, [currentArticle.content])
  61.   // 更改当前文档
  62.   const changeCurrentArticle = async (url: string) => {
  63.     const res = await fetch(url);
  64.     const content = await res.text();
  65.     setCurrentArticle({ ...currentArticle, content, url })
  66.   }
  67.   // 书籍导航点击
  68.   const menuOnClick = (e: any) => {
  69.     const url = articles[e.key]
  70.     changeCurrentArticle(url)
  71.   }
  72.   // 转换为文章右侧目录
  73.   const transArticleNavs = (navs: any) => {
  74.     // 转换为二级导航
  75.     const treedevelopDocs = navsToTree(navs);
  76.     setTreeNavs(treedevelopDocs)
  77.   }
  78.   return (
  79.     <>
  80.       <Row className='articles'>
  81.         <Col flex='200px' className="articles-list">
  82.           <Affix offsetTop={24}>
  83.             <Menu defaultSelectedKeys={['1']} onClick={menuOnClick} theme='light'>
  84.               <Menu.Item key="1">开发文档</Menu.Item>
  85.               <Menu.Item key="2">使用文档</Menu.Item>
  86.             </Menu>
  87.           </Affix>
  88.         </Col>
  89.         <Col flex='1' className='articles-content'>
  90.           <div className='articles-content_wrpper'>
  91.             <ReactMarkdown
  92.               className="markdown-body"
  93.               source={currentArticle.content}
  94.               escapeHtml={false}
  95.               renderers={{
  96.                 heading: HeadBlock
  97.               }}
  98.             />
  99.           </div>
  100.         </Col>
  101.         <Col flex='200px' className="articles-menu">
  102.           <Affix offsetTop={20} >
  103.             <Anchor style={{ width: 160 }}>
  104.               {
  105.                 treeNavs.map((item: any) => {
  106.                   if (item.children) {
  107.                     return (
  108.                       <Link href={`###${item.nodeKey}`} title={item.value} key={item.nodeKey}>
  109.                         {
  110.                           item.children.map((childItem: any) => (
  111.                             <Link href={`###${childItem.nodeKey}`} title={childItem.value} key={childItem.nodeKey} />
  112.                           ))
  113.                         }
  114.                       </Link>
  115.                     )
  116.                   } else {
  117.                     return (
  118.                       <Link href={`###${item.nodeKey}`} title={item.value} key={item.nodeKey} />
  119.                     )
  120.                   }
  121.                 })
  122.               }
  123.             </Anchor>
  124.           </Affix>
  125.         </Col>
  126.       </Row>
  127.     </>
  128.   );
  129. };
  130. export default NormalTest;
  1. import React from 'react';
  2. const HeadBlock = (props) => {
  3.   const { level, children } = props;
  4.   const { nodeKey } = children[0].props;
  5.   return (
  6.     <>
  7.       {React.createElement(`h${level}`, { className: 'article-nav', id: nodeKey, 'data-level': level }, children)}
  8.     </>
  9.   );
  10. }
  11. export default HeadBlock;

cytoscape | cytoscape-dagre

https://www.npmjs.com/package/cytoscape

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

Lodash

https://www.npmjs.com/package/lodash

==功能==:函数工具类库

  1. // Load the full build.
  2. var _ = require('lodash');
  3. // Load the core build.
  4. var _ = require('lodash/core');
  5. // Load the FP build for immutable auto-curried iteratee-first data-last methods.
  6. var fp = require('lodash/fp');
  7.  
  8. // Load method categories.
  9. var array = require('lodash/array');
  10. var object = require('lodash/fp/object');
  11.  
  12. // Cherry-pick methods for smaller browserify/rollup/webpack bundles.
  13. var at = require('lodash/at');
  14. var curryN = require('lodash/fp/curryN');

patch-package node

https://www.npmjs.com/package/patch-package

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

cross-env node

https://www.npmjs.com/package/cross-env

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

  1. npm install --save-dev cross-env
  2. {
  3.   "scripts": {
  4.     "parentScript""cross-env GREET=\"Joe\" npm run childScript",
  5.     "childScript""cross-env-shell \"echo Hello $GREET\""
  6.   }
  7. }

bignumber.js

https://www.npmjs.com/package/bignumber.js

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

  1. https://mikemcl.github.io/bignumber.js/
  2. https://juejin.cn/post/6844903704714280968###heading-7

QRCode.js、 qrcode.vue

https://www.npmjs.com/package/qrcodejs2

https://www.npmjs.com/package/qrcode.vue

==功能==:

  1. npm install --save qrcode.vue
  2. npm i qrcodejs2
  3.    getBlob(base64) {
  4.       const mimeString = base64.split(',')[0].split(':')[1].split(';')[0]; // mime类型
  5.       const byteString = atob(base64.split(',')[1]); // base64 解码
  6.       const arrayBuffer = new ArrayBuffer(byteString.length); // 创建缓冲数组
  7.       const intArray = new Uint8Array(arrayBuffer); // 创建视图
  8.       for (let i = 0; i < byteString.length; i += 1) {
  9.         intArray[i] = byteString.charCodeAt(i);
  10.       }
  11.       return new Blob([intArray], {
  12.         type: mimeString,
  13.       });
  14.     },
  15.     savePicture(Url = this.qrcodeUrl) {
  16.       const blob = new Blob([''], { type'application/octet-stream' });
  17.       const url = URL.createObjectURL(blob);
  18.       const a = document.createElement('a');
  19.       a.href = Url;
  20.       // eslint-disable-next-line prefer-destructuring
  21.       a.download = Url.replace(/(.*\/)*([^.]+.*)/gi, '$2').split('?')[0];
  22.       const e = document.createEvent('MouseEvents');
  23.       e.initMouseEvent(
  24.         'click',
  25.         true,
  26.         false,
  27.         window,
  28.         0,
  29.         0,
  30.         0,
  31.         0,
  32.         0,
  33.         false,
  34.         false,
  35.         false,
  36.         false,
  37.         0,
  38.         null,
  39.       );
  40.       a.dispatchEvent(e);
  41.       URL.revokeObjectURL(url);
  42.     },
  43.     _qrcode(url) {
  44.       const div = document.createElement('div');
  45.       // eslint-disable-next-line new-cap
  46.       const code = new QRCode(div, {
  47.         text: url,
  48.         width: 500,
  49.         height: 500,
  50.         colorDark: '###000000',
  51.         colorLight: '###ffffff',
  52.         correctLevel: QRCode.CorrectLevel.L,
  53.       });
  54.       // 这里如果需要在页面上展示的话,就将div节点给添加到dom树上去;node.appendChild(div)
  55.       const canvas = code._el.querySelector('canvas'); // 获取生成二维码中的canvas,并将canvas转换成base64
  56.       const base64Text = canvas.toDataURL('image/png');
  57.       const blob = this.getBlob(base64Text); // 将base64转换成blob对象
  58.       return window.URL.createObjectURL(blob);
  59.     },

cssnano、js-beautify

https://www.npmjs.com/package/cssnano

https://www.npmjs.com/package/js-beautify

==功能==:css js 压缩工具

cors node

https://www.npmjs.com/package/cors

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

  1. npm install cors
  2. var cors = require('cors');
  3. app.use(
  4.   cors({
  5.     origin: ['http://localhost:8000'],
  6.     methods: ['GET''POST'],
  7.     alloweHeaders: ['Conten-Type''Authorization'],
  8.   })
  9. );

countup.js

https://www.npmjs.com/package/countup.js

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

  1. npm i countup.js
  2. interface CountUpOptions {
  3.   startVal?: number; // number to start at (0)
  4.   decimalPlaces?: number; // number of decimal places (0)
  5.   duration?: number; // animation duration in seconds (2)
  6.   useGrouping?: boolean; // example: 1,000 vs 1000 (true)
  7.   useEasing?: boolean; // ease animation (true)
  8.   smartEasingThreshold?: number; // smooth easing for large numbers above this if useEasing (999)
  9.   smartEasingAmount?: number; // amount to be eased for numbers above threshold (333)
  10.   separator?: string// grouping separator (',')
  11.   decimal?: string// decimal ('.')
  12.   // easingFn: easing function for animation (easeOutExpo)
  13.   easingFn?: (t: number, b: number, c: number, d: number) => number;
  14.   formattingFn?: (n: number) => string// this function formats result
  15.   prefix?: string// text prepended to result
  16.   suffix?: string// text appended to result
  17.   numerals?: string[]; // numeral glyph substitution
  18. }

js-base64

https://www.npmjs.com/package/js-base64

==功能==:另一个Base64转码器。

  1. npm install --save js-base64
  2. require=require('esm')(module);
  3. import {Base64} from 'js-base64';
  4. let latin = 'dankogai';
  5. let utf8  = '小飼弾'
  6. let u8s   =  new Uint8Array([100,97,110,107,111,103,97,105]);
  7. Base64.encode(latin);             // ZGFua29nYWk=
  8. Base64.btoa(latin);               // ZGFua29nYWk=
  9. Base64.btoa(utf8);                // raises exception
  10. Base64.fromUint8Array(u8s);       // ZGFua29nYWk=
  11. Base64.fromUint8Array(u8s, true); // ZGFua29nYW which is URI safe
  12. Base64.encode(utf8);              // 5bCP6aO85by+
  13. Base64.encode(utf8, true)         // 5bCP6aO85by-
  14. Base64.encodeURI(utf8);           // 5bCP6aO85by-

json-bigint

https://www.npmjs.com/package/json-bigint

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

  1. var JSONbig = require('json-bigint');
  2.  
  3. var json = '{ "value" : 9223372036854775807, "v2": 123 }';
  4. console.log('Input:', json);
  5. console.log('');
  6.  
  7. console.log('node.js built-in JSON:');
  8. var r = JSON.parse(json);
  9. console.log('JSON.parse(input).value : ', r.value.toString());
  10. console.log('JSON.stringify(JSON.parse(input)):', JSON.stringify(r));
  11.  
  12. console.log('\n\nbig number JSON:');
  13. var r1 = JSONbig.parse(json);
  14. console.log('JSONbig.parse(input).value : ', r1.value.toString());
  15. console.log('JSONbig.stringify(JSONbig.parse(input)):', JSONbig.stringify(r1));

vuejs-datetimepicker

https://www.npmjs.com/package/vuejs-datetimepicker

==功能==:

  1. npm install vuejs-datetimepicker
  2. <template>
  3.     <datetime format="MM/DD/YYYY" width="300px" v-model="val"></datetime>
  4. </template>
  5.  
  6. <script>
  7. import datetime from 'vuejs-datetimepicker';
  8.  
  9. export default {
  10.     components: { datetime }
  11. };
  12. </script>

vue-meta-info

https://www.npmjs.com/package/vue-meta-info

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

  1. <template>
  2. ...
  3. </template>
  4. <script>
  5. export default {
  6. metaInfo: {
  7. title: 'My Example App', // set a title
  8. meta: [{ // set meta
  9. name: 'keyWords',
  10. content: 'My Example App'
  11. }]
  12. link: [{ // set link
  13. rel: 'asstes',
  14. href: 'https://assets-cdn.github.com/'
  15. }]
  16. }
  17. }
  18. </script>

vue-smooth-scroll

https://www.npmjs.com/package/vue-smooth-scroll

==功能==:Scroll

  1. npm install --save vue-smooth-scroll
  2. import vueSmoothScroll from 'vue-smooth-scroll'
  3. Vue.use(vueSmoothScroll)

prismjs

https://www.npmjs.com/package/prismjs

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

vuex-persistedstate

https://www.npmjs.com/package/vuex-persistedstate

==功能==:

  1. npm install --save vuex-persistedstate
  2. import createPersistedState from 'vuex-persistedstate';
  3. import * as Cookies from 'js-cookie';
  4. import cookie from 'cookie';
  5.  
  6. export default ({ store, req }) => {
  7.     createPersistedState({
  8.         paths: [...],
  9.         storage: {
  10.             getItem: (key) => {
  11.                 // See https://nuxtjs.org/guide/plugins/###using-process-flags
  12.                 if (process.server) {
  13.                     const parsedCookies = cookie.parse(req.headers.cookie);
  14.                     return parsedCookies[key];
  15.                 } else {
  16.                     return Cookies.get(key);
  17.                 }
  18.             },
  19.             // Please see https://github.com/js-cookie/js-cookie###json, on how to handle JSON.
  20.             setItem: (key, value) =>
  21.                 Cookies.set(key, value, { expires: 365, secure: false }),
  22.             removeItem: key => Cookies.remove(key)
  23.         }
  24.     })(store);
  25. };

vue-slider-component

https://github.com/NightCatSama/vue-slider-component/blob/master/README-CN.md

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

  1. $ yarn add vue-slider-component
  2. ### npm install vue-slider-component --save
  3. <template>
  4.   <vue-slider v-model="value" />
  5. </template>
  6. <script>
  7. import VueSlider from 'vue-slider-component'
  8. import 'vue-slider-component/theme/antd.css'
  9. export default {
  10.   components: {
  11.     VueSlider
  12.   },
  13.   data () {
  14.     return {
  15.       value: 0
  16.     }
  17.   }
  18. }
  19. </script>

CodeMirror

https://www.npmjs.com/package/codemirror

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

vue-codemirror

https://www.npmjs.com/package/vue-codemirror

==功能==:

  1. <codemirror
  2.         ref="editQuerySQL"
  3.         @ready="onCodemirrorReady"
  4.         @input="onCodemirrorInput"
  5.         v-model="query.sql"
  6.         :options="cmOptions"
  7.       ></codemirror>
  8.       
  9.       
  10. import { codemirror } from 'vue-codemirror';
  11. import { getEthdb } from '@/api';
  12. import 'codemirror/lib/codemirror.css';
  13. import 'codemirror/theme/idea.css';
  14. // import 'codemirror/theme/base16-dark.css';
  15. import 'codemirror/theme/panda-syntax.css';
  16. import 'codemirror/addon/hint/show-hint.css';
  17. import 'codemirror/lib/codemirror';
  18. import 'codemirror/mode/sql/sql';
  19. import 'codemirror/addon/hint/show-hint';
  20. import 'codemirror/addon/hint/sql-hint';
  21.         
  22. export default {
  23.     data(){
  24.         retrun {
  25.             query: {
  26.                 sql: 'SELECT * FROM ethblock LIMIT 200',
  27.              },
  28.               cmOptions: {
  29.                 scroll: false,
  30.                 tabSize: 4,
  31.                 lineNumbers: false,
  32.                 line: false,
  33.                 indentWithTabs: true,
  34.                 smartIndent: true,
  35.                 autofocus: false,
  36.                 mode: 'text/x-mariadb',
  37.                 theme: 'idea',
  38.                 hintOptions: {
  39.                   completeSingle: false,
  40.                 },
  41.               },
  42.         }
  43.     },
  44.     methods:{
  45.      onCodemirrorReady(cm) {
  46.       cm.on('keypress', () => {
  47.         cm.showHint();
  48.       });
  49.     },
  50.      onCodemirrorInput(newQuery) {
  51.       this.query.sql = newQuery;
  52.     },
  53.     }
  54.     
  55.     
  56. }

portfinder || get-port node

https://www.npmjs.com/package/portfinder

https://www.npmjs.com/package/get-port

==功能==:端口查看器

  1. [sudo] npm install portfinder
  2. portfinder.getPort({
  3.     port: 3000,    // minimum port
  4.     stopPort: 3333 // maximum port
  5. }, callback);

regedit node

https://www.npmjs.com/package/regedit

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

lowdb

https://www.npmjs.com/package/lowdb

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

  1. npm install lowdb
  2. const low = require('lowdb')
  3. const FileSync = require('lowdb/adapters/FileSync')
  4.  
  5. const adapter = new FileSync('db.json')
  6. const db = low(adapter)
  7.  
  8. // Set some defaults
  9. db.defaults({ posts: [], user: {} })
  10.   .write()
  11.  
  12. // Add a post
  13. db.get('posts')
  14.   .push({ id: 1, title: 'lowdb is awesome'})
  15.   .write()
  16.  
  17. // Set a user using Lodash shorthand syntax
  18. db.set('user.name''typicode')
  19.   .write()

cheerio node

https://github.com/cheeriojs/cheerio/wiki/Chinese-README

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

  1. npm install cheerio
  2. const cheerio = require('cheerio');
  3. const $ = cheerio.load('<h2 class="title">Hello world</h2>');
  4. $('h2.title').text('Hello there!');
  5. $('h2').addClass('welcome');
  6. $.html();
  7. //=> <html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>

libxmljs

https://github.com/libxmljs/libxmljs/wiki

==功能==:解析xml

node-fetch、 got node

https://github.com/node-fetch/node-fetch

https://github.com/sindresorhus/got###readme

==功能==:node-ajax

ora node

https://www.npmjs.com/package/ora

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

  1. const ora = require('ora');
  2.  
  3. const spinner = ora('Loading unicorns').start();
  4.  
  5. setTimeout(() => {
  6.     spinner.color = 'yellow';
  7.     spinner.text = 'Loading rainbows';
  8. }, 1000);

node-mkdirp 、rimraf node

https://github.com/substack/node-mkdirp

https://www.npmjs.com/package/rimraf

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

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

shelljs

https://www.npmjs.com/package/shelljs

==功能==:hellJS是在Node.js API之上的Unix shell命令的可移植(Windows / Linux / OS X)实现。您可以使用它消除shell脚本对Unix的依赖,同时仍然保留其熟悉而强大的命令。您还可以全局安装它,以便可以从Node项目外部运行它-告别那些讨厌的Bash脚本!

  1. var shell = require('shelljs');
  2.  
  3. if (!shell.which('git')) {
  4.   shell.echo('Sorry, this script requires git');
  5.   shell.exit(1);
  6. }
  7.  
  8. // Copy files to release dir
  9. shell.rm('-rf''out/Release');
  10. shell.cp('-R''stuff/''out/Release');
  11.  
  12. // Replace macros in each .js file
  13. shell.cd('lib');
  14. shell.ls('*.js').forEach(function (file) {
  15.   shell.sed('-i''BUILD_VERSION''v0.1.2', file);
  16.   shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
  17.   shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
  18. });
  19. shell.cd('..');

shx

https://www.npmjs.com/package/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/").

  1. npm install shx --save-dev
  2. package.json:
  3. {
  4.   "scripts": {
  5.     "clean""shx rm -rf build dist && shx echo Done"
  6.   }
  7. }

node-ssh

https://github.com/steelbrain/node-ssh###readme

==功能==:Node-SSH 是 ssh2的一个非常轻量级的 Promise 包装器。

chalk

https://github.com/chalk/chalk

==功能==:给终端嵌套您想要的样式。

  1. const chalk = require('chalk');
  2. const log = console.log;
  3. // Combine styled and normal strings
  4. log(chalk.blue('Hello') + ' World' + chalk.red('!'));
  5. // Compose multiple styles using the chainable API
  6. log(chalk.blue.bgRed.bold('Hello world!'));
  7. // Pass in multiple arguments
  8. log(chalk.blue('Hello''World!''Foo''bar''biz''baz'));
  9. // Nest styles
  10. log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
  11. // Nest styles of the same type even (color, underline, background)
  12. log(chalk.green(
  13.     'I am a green line ' +
  14.     chalk.blue.underline.bold('with a blue substring') +
  15.     ' that becomes green again!'
  16. ));

Nzh

https://blog.whyoop.com/nzh/docs/###/

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

  • 以字符串的方式转换,没有超大数及浮点数等问题(请自行对原数据进行四舍五入等操作)

  • 支持科学记数法字符串的转换

  • 支持口语化

  • 支持自定义转换(不论是兆,京还是厘都可以用)

  • 对超大数支持用争议教少的万万亿代替亿亿

  • 当然,你还可以把中文数字再转回阿拉伯数字

  1. npm install nzh --save
  2. var Nzh = require("nzh");
  3. var nzhcn = require("nzh/cn"); //直接使用简体中文
  4. var nzhhk = require("nzh/hk"); //繁体中文
  5. var nzhcn = Nzh.cn;                 // 使用简体中文,  另外有 Nzh.hk -- 繁体中文
  6. nzhcn.encodeS(100111);              // 转中文小写 >> 十万零一百一十一
  7. nzhcn.encodeB(100111);              // 转中文大写 >> 壹拾万零壹佰壹拾壹
  8. nzhcn.encodeS("1.23456789e+21");    // 科学记数法字符串 >> 十二万三千四百五十六万万七千八百九十万亿
  9. nzhcn.toMoney("100111.11");         // 转中文金额 >> 人民币壹拾万零壹佰壹拾壹元壹角壹分

decko

https://github.com/developit/decko

节流 防抖https://blog.csdn.net/qq_2955...==功能==:三个最有用的装饰器的简洁实现:

  • @bind:this在方法内使常量的值

  • @debounce:限制对方法的调用

  • @memoize:根据参数缓存返回值

npm i -S decko

p-queue

https://github.com/sindresorhus/p-queue###readme

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

  1. const {default: PQueue} = require('p-queue');
  2. const got = require('got');
  3. const queue = new PQueue({concurrency: 1});
  4. (async () => {
  5.     await queue.add(() => got('https://sindresorhus.com'));
  6.     console.log('Done: sindresorhus.com');
  7. })();
  8. (async () => {
  9.     await queue.add(() => got('https://avajs.dev'));
  10.     console.log('Done: avajs.dev');
  11. })();
  12. (async () => {
  13.     const task = await getUnicornTask();
  14.     await queue.add(task);
  15.     console.log('Done: Unicorn task');
  16. })();

sleep

https://www.npmjs.com/package/sleep

==功能==:sleep

  1. npm i sleep
  2. var sleep = require('sleep');
  3. function msleep(n) {
  4.   Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 00, n);
  5. }
  6. function sleep(n) {
  7.   msleep(n*1000);
  8. }

delay

https://github.com/sindresorhus/delay###readme

==功能==:将承诺推迟一定的时间

  1. npm install delay
  2. const delay = require('delay');
  3. (async () => {
  4.     bar();
  5.     await delay(100);
  6.     // Executed 100 milliseconds later
  7.     baz();
  8. })();

better-scroll

https://github.com/ustbhuangyi/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

https://github.com/HenrikJoreteg/create-keyframe-animation

==功能==:使用JavaScrip在浏览器中动态生成CSS关键帧动画(不维护了)

vconsole

https://github.com/Tencent/vConsole/blob/HEAD/README_CN.md

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

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

源自:https://segmentfault.com/a/1190000038589634

声明:文章著作权归作者所有,如有侵权,请联系小编删除。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/179449
推荐阅读
相关标签
  

闽ICP备14008679号