Licia:最全最实用的 JavaScript 工具库

前言

在业务开发过程中,我们经常会重复使用日期格式化cookie 操作模板浏览器判断类型判断等功能。为了避免不同项目之间进行复制粘贴,可以将这些常用的函数封装到一起并发布 npm 包。在将近三年的前端开发工作中,笔者将自己平时用到的工具库统统封装到了一个项目中 Licia。目前所包含模块已达三百个,基本可以满足前端的日常工发需求。如果你对该项目感兴趣,欢迎试用并帮忙持续改进:)

使用方法

一、安装 npm 包

首先安装 npm 包到本地。

npm i licia --save

安装完之后,你就可以直接在项目中引用模块了,就像使用 lodash 一样。

var uuid = require('licia/uuid');

console.log(uuid()); // -> 0e3b84af-f911-4a55-b78a-cedf6f0bd815

二、使用打包工具

该项目自带打包工具 eustia,可以通过配置文件或命令行扫描源码自动生成项目专用的工具库。

npm i eustia -g

假设你想html文件中使用trim方法,先直接在代码中使用:

<html>
<head>
    <meta charset="utf-8"/>
    <title>Eustia</title>
    <script src="util.js"></script>
</head>
<body>
    <script>
    var projectName = _.trim(' Eustia ');
    // Some code...
    </script>
</body>
</html>

然后跑下命令:

eustia build

该工具会扫描你的html代码并生成一个util.js(默认文件名)文件,大功告成!

PS: 之前做的手机调试工具 eruda 源码里的 util.js 就是使用该工具生成的:)

三、使用在线工具生成 util 库

你可以直接访问 https://eustia.liriliri.io/builder.html 在输入框输入需要的工具函数(以逗号分隔),然后点击下载 util.js 文件并将该文件放入项目中去即可。

支持模块汇总

因字数限制,这里只简单列出函数及其功能介绍,详细的用法请访问 https://eustia.liriliri.io/module.html 查看。

  1. $: jQuery like style dom manipulator.
  2. $attr: Element attribute manipulation.
  3. $class: Element class manipulations.
  4. $css: Element css manipulation.
  5. [$data](https://eustia.liriliri.io/module.html#dollar-data): Wrapper of $attr, adds data- prefix to keys.
  6. $event: bind events to certain dom elements.
  7. $insert: Insert html on different position.
  8. $offset: Get the position of the element in document.
  9. $property: Element property html, text, val getter and setter.
  10. $remove: Remove the set of matched elements from the DOM.
  11. $safeEls: Convert value into an array, if it’s a string, do querySelector.
  12. $show: Show elements.
  13. Blob: Use Blob when available, otherwise BlobBuilder.
  14. Class: Create JavaScript class.
  15. Color: Color converter.
  16. Dispatcher: Flux dispatcher.
  17. Emitter: Event emitter class which provides observer pattern.
  18. Enum: Enum type implementation.
  19. JsonTransformer: Json to json transformer.
  20. LinkedList: Doubly-linked list implementation.
  21. LocalStore: LocalStorage wrapper.
  22. Logger: Simple logger with level filter.
  23. MutationObserver: Safe MutationObserver, does nothing if MutationObserver is not supported.
  24. Promise: Lightweight Promise implementation.
  25. Queue: Queue data structure.
  26. ReduceStore: Simplified redux like state container.
  27. Select: Simple wrapper of querySelectorAll to make dom selection easier.
  28. SessionStore: SessionStorage wrapper.
  29. Stack: Stack data structure.
  30. State: Simple state machine.
  31. Store: Memory storage.
  32. Tween: Tween engine for JavaScript animations.
  33. Url: Simple url manipulator.
  34. Validator: Object values validation.
  35. abbrev: Calculate the set of unique abbreviations for a given set of strings.
  36. after: Create a function that invokes once it’s called n or more times.
  37. ajax: Perform an asynchronous HTTP request.
  38. allKeys: Retrieve all the names of object’s own and inherited properties.
  39. arrToMap: Make an object map using array of strings.
  40. atob: Use Buffer to emulate atob when running in node.
  41. average: Get average value of given numbers.
  42. base64: Basic base64 encoding and decoding.
  43. before: Create a function that invokes less than n times.
  44. bind: Create a function bound to a given object.
  45. btoa: Use Buffer to emulate btoa when running in node.
  46. bubbleSort: Bubble sort implementation.
  47. callbackify: Convert a function that returns a Promise to a function following the error-first callback style.
  48. camelCase: Convert string to “camelCase”.
  49. capitalize: Convert the first character to upper case and the remaining to lower case.
  50. castPath: Cast value into a property path array.
  51. centerAlign: Center align text in a string.
  52. char: Return string representing a character whose Unicode code point is the given integer.
  53. chunk: Split array into groups the length of given size.
  54. clamp: Clamp number within the inclusive lower and upper bounds.
  55. className: Utility for conditionally joining class names.
  56. clone: Create a shallow-copied clone of the provided plain object.
  57. cloneDeep: Recursively clone value.
  58. cmpVersion: Compare version strings.
  59. compact: Return a copy of the array with all falsy values removed.
  60. compose: Compose a list of functions.
  61. compressImg: Compress image using canvas.
  62. concat: Concat multiple arrays into a single array.
  63. contain: Check if the value is present in the list.
  64. convertBase: Convert base of a number.
  65. cookie: Simple api for handling browser cookies.
  66. copy: Copy text to clipboard using document.execCommand.
  67. createAssigner: Used to create extend, extendOwn and defaults.
  68. createUrl: CreateObjectURL wrapper.
  69. cssSupports: Check if browser supports a given CSS feature.
  70. curry: Function currying.
  71. dateFormat: Simple but extremely useful date format function.
  72. debounce: Return a new debounced version of the passed function.
  73. debug: A tiny JavaScript debugging utility.
  74. decodeUriComponent: Better decodeURIComponent that does not throw if input is invalid.
  75. defaults: Fill in undefined properties in object with the first value present in the following list of defaults objects.
  76. define: Define a module, should be used along with use.
  77. defineProp: Shortcut for Object.defineProperty(defineProperties).
  78. delay: Invoke function after certain milliseconds.
  79. delegate: Event delegation.
  80. detectBrowser: Detect browser info using ua.
  81. detectOs: Detect operating system using ua.
  82. difference: Create an array of unique array values not included in the other given array.
  83. dotCase: Convert string to “dotCase”.
  84. download: Trigger a file download on client side.
  85. each: Iterate over elements of collection and invokes iteratee for each element.
  86. easing: Easing functions adapted from http://jqueryui.com/
  87. endWith: Check if string ends with the given target string.
  88. escape: Escapes a string for insertion into HTML, replacing &, <, >, “, `, and ‘ characters.
  89. escapeJsStr: Escape string to be a valid JavaScript string literal between quotes.
  90. escapeRegExp: Escape special chars to be used as literals in RegExp constructors.
  91. evalCss: Load css into page.
  92. evalJs: Execute js in given context.
  93. every: Check if predicate return truthy for all elements.
  94. extend: Copy all of the properties in the source objects over to the destination object.
  95. extendDeep: Recursive object extending.
  96. extendOwn: Like extend, but only copies own properties over to the destination object.
  97. extractBlockCmts: Extract block comments from source code.
  98. extractUrls: Extract urls from plain text.
  99. fetch: Turn XMLHttpRequest into promise like.
  100. fibonacci: Calculate fibonacci number.
  101. fileSize: Turn bytes into human readable file size.
  102. fill: Fill elements of array with value.
  103. filter: Iterates over elements of collection, returning an array of all the values that pass a truth test.
  104. find: Find the first value that passes a truth test in a collection.
  105. findIdx: Return the first index where the predicate truth test passes.
  106. findKey: Return the first key where the predicate truth test passes.
  107. findLastIdx: Return the last index where the predicate truth test passes.
  108. flatten: Recursively flatten an array.
  109. fnParams: Get a function parameter’s names.
  110. format: Format string in a printf-like format.
  111. fraction: Convert number to fraction.
  112. freeze: Shortcut for Object.freeze.
  113. freezeDeep: Recursively use Object.freeze.
  114. gcd: Compute the greatest common divisor using Euclid’s algorithm.
  115. getUrlParam: Get url param.
  116. has: Checks if key is a direct property.
  117. hotkey: Capture keyboard input to trigger given events.
  118. hslToRgb: Convert hsl to rgb.
  119. identity: Return the first argument given.
  120. idxOf: Get the index at which the first occurrence of value.
  121. indent: Indent each line in a string.
  122. inherits: Inherit the prototype methods from one constructor into another.
  123. insertionSort: Insertion sort implementation.
  124. intersect: Compute the list of values that are the intersection of all the arrays.
  125. intersectRange: Intersect two ranges.
  126. invert: Create an object composed of the inverted keys and values of object.
  127. isAbsoluteUrl: Check if an url is absolute.
  128. isArgs: Check if value is classified as an arguments object.
  129. isArr: Check if value is an Array object.
  130. isArrBuffer: Check if value is an ArrayBuffer.
  131. isArrLike: Check if value is array-like.
  132. isBlob: Check if value is a Blob.
  133. isBool: Check if value is a boolean primitive.
  134. isBrowser: Check if running in a browser.
  135. isBuffer: Check if value is a buffer.
  136. isClose: Check if values are close(almost equal) to each other.
  137. isDataUrl: Check if a string is a valid data url.
  138. isDate: Check if value is classified as a Date object.
  139. isEl: Check if value is a DOM element.
  140. isEmail: Loosely validate an email address.
  141. isEmpty: Check if value is an empty object or array.
  142. isEqual: Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.
  143. isErr: Check if value is an error.
  144. isEven: Check if number is even.
  145. isFile: Check if value is a file.
  146. isFinite: Check if value is a finite primitive number.
  147. isFn: Check if value is a function.
  148. isGeneratorFn: Check if value is a generator function.
  149. isInt: Checks if value is classified as a Integer.
  150. isJson: Check if value is a valid JSON.
  151. isLeapYear: Check if a year is a leap year.
  152. isMatch: Check if keys and values in src are contained in obj.
  153. isMiniProgram: Check if running in wechat mini program.
  154. isMobile: Check whether client is using a mobile browser using ua.
  155. isNaN: Check if value is an NaN.
  156. isNative: Check if value is a native function.
  157. isNil: Check if value is null or undefined, the same as value == null.
  158. isNode: Check if running in node.
  159. isNull: Check if value is an Null.
  160. isNum: Check if value is classified as a Number primitive or object.
  161. isNumeric: Check if value is numeric.
  162. isObj: Check if value is the language type of Object.
  163. isOdd: Check if number is odd.
  164. isPlainObj: Check if value is an object created by Object constructor.
  165. isPrimitive: Check if value is string, number, boolean or null.
  166. isPromise: Check if value looks like a promise.
  167. isRegExp: Check if value is a regular expression.
  168. isRelative: Check if path appears to be relative.
  169. isRetina: Determine if running on a high DPR device or not.
  170. isStr: Check if value is a string primitive.
  171. isStream: Check if value is a Node.js stream.
  172. isTypedArr: Check if value is a typed array.
  173. isUndef: Check if value is undefined.
  174. isUrl: Loosely validate an url.
  175. isWindows: Check if platform is windows.
  176. jsonp: A simple jsonp implementation.
  177. kebabCase: Convert string to “kebabCase”.
  178. keyCode: Key codes and key names conversion.
  179. keys: Create an array of the own enumerable property names of object.
  180. last: Get the last element of array.
  181. lazyRequire: Require modules lazily.
  182. linkify: Hyperlink urls in a string.
  183. loadCss: Inject link tag into page with given href value.
  184. loadImg: Load image with given src.
  185. loadJs: Inject script tag into page with given src value.
  186. longest: Get the longest item in an array.
  187. lowerCase: Convert string to lower case.
  188. lpad: Pad string on the left side if it’s shorter than length.
  189. ltrim: Remove chars or white-spaces from beginning of string.
  190. map: Create an array of values by running each element in collection through iteratee.
  191. mapObj: Map for objects.
  192. matcher: Return a predicate function that checks if attrs are contained in an object.
  193. max: Get maximum value of given numbers.
  194. memStorage: Memory-backed implementation of the Web Storage API.
  195. memoize: Memoize a given function by caching the computed result.
  196. meta: Document meta manipulation, turn name and content into key value pairs.
  197. methods: Return a sorted list of the names of every method in an object.
  198. min: Get minimum value of given numbers.
  199. mkdir: Recursively create directories.
  200. moment: Tiny moment.js like implementation.
  201. ms: Convert time string formats to milliseconds.
  202. negate: Create a function that negates the result of the predicate function.
  203. nextTick: Next tick for both node and browser.
  204. noop: A no-operation function.
  205. normalizePath: Normalize file path slashes.
  206. now: Gets the number of milliseconds that have elapsed since the Unix epoch.
  207. objToStr: Alias of Object.prototype.toString.
  208. omit: Opposite of pick.
  209. once: Create a function that invokes once.
  210. optimizeCb: Used for function context binding.
  211. orientation: Screen orientation helper.
  212. pad: Pad string on the left and right sides if it’s shorter than length.
  213. pairs: Convert an object into a list of [key, value] pairs.
  214. parallel: Run an array of functions in parallel.
  215. parseArgs: Parse command line argument options, the same as minimist.
  216. partial: Partially apply a function by filling in given arguments.
  217. pascalCase: Convert string to “pascalCase”.
  218. perfNow: High resolution time up to microsecond precision.
  219. pick: Return a filtered copy of an object.
  220. pluck: Extract a list of property values.
  221. precision: Find decimal precision of a given number.
  222. prefix: Add vendor prefixes to a CSS attribute.
  223. promisify: Convert callback based functions into Promises.
  224. property: Return a function that will itself return the key property of any passed-in object.
  225. query: Parse and stringify url query strings.
  226. raf: Shortcut for requestAnimationFrame.
  227. random: Produces a random number between min and max(inclusive).
  228. randomBytes: Random bytes generator.
  229. range: Create flexibly-numbered lists of integers.
  230. ready: Invoke callback when dom is ready, similar to jQuery ready.
  231. reduce: Turn a list of values into a single value.
  232. reject: Opposite of filter.
  233. remove: Remove all elements from array that predicate returns truthy for and return an array of the removed elements.
  234. repeat: Repeat string n-times.
  235. restArgs: This accumulates the arguments passed into an array, after a given index.
  236. rgbToHsl: Convert rgb to hsl.
  237. rmCookie: Loop through all possible path and domain to remove cookie.
  238. rmdir: Recursively remove directories.
  239. root: Root object reference, global in nodeJs, window in browser.
  240. rpad: Pad string on the right side if it’s shorter than length.
  241. rtrim: Remove chars or white-spaces from end of string.
  242. safeCb: Create callback based on input value.
  243. safeDel: Delete object property.
  244. safeGet: Get object property, don’t throw undefined error.
  245. safeSet: Set value at path of object.
  246. safeStorage: Use storage safely in safari private browsing and older browsers.
  247. sample: Sample random values from a collection.
  248. scrollTo: Scroll to a target with animation.
  249. selectionSort: Selection sort implementation.
  250. shuffle: Randomize the order of the elements in a given array.
  251. size: Get size of object, length of array like object or the number of keys.
  252. slice: Create slice of source array or array-like object.
  253. snakeCase: Convert string to “snakeCase”.
  254. some: Check if predicate return truthy for any element.
  255. spaceCase: Convert string to “spaceCase”.
  256. splitCase: Split different string case to an array.
  257. splitPath: Split path into device, dir, name and ext.
  258. startWith: Check if string starts with the given target string.
  259. strHash: String hash function using djb2.
  260. stringify: JSON stringify with support for circular object, function etc.
  261. stripAnsi: Strip ansi codes from a string.
  262. stripCmt: Strip comments from source code.
  263. stripColor: Strip ansi color codes from a string.
  264. stripHtmlTag: Strip html tags from a string.
  265. sum: Compute sum of given numbers.
  266. template: Compile JavaScript template into function that can be evaluated for rendering.
  267. throttle: Return a new throttled version of the passed function.
  268. through: Tiny wrapper of stream Transform.
  269. timeAgo: Format datetime with * time ago statement.
  270. timeTaken: Get execution time of a function.
  271. toArr: Convert value to an array.
  272. toBool: Convert value to a boolean.
  273. toDate: Convert value to a Date.
  274. toEl: Convert html string to dom elements.
  275. toInt: Convert value to an integer.
  276. toNum: Convert value to a number.
  277. toSrc: Convert function to its source code.
  278. toStr: Convert value to a string.
  279. topoSort: Topological sorting algorithm.
  280. trigger: Trigger browser events.
  281. trim: Remove chars or white-spaces from beginning end of string.
  282. tryIt: Run function in a try catch.
  283. type: Determine the internal JavaScript [[Class]] of an object.
  284. ucs2: UCS-2 encoding and decoding.
  285. unescape: Convert HTML entities back, the inverse of escape.
  286. union: Create an array of unique values, in order, from all given arrays.
  287. uniqId: Generate a globally-unique id.
  288. unique: Create duplicate-free version of an array.
  289. unzip: Opposite of zip.
  290. upperCase: Convert string to upper case.
  291. upperFirst: Convert the first character of string to upper case.
  292. use: Use modules that is created by define.
  293. utf8: UTF-8 encoding and decoding.
  294. uuid: RFC4122 version 4 compliant uuid generator.
  295. values: Create an array of the own enumerable property values of object.
  296. viewportScale: Get viewport scale.
  297. waterfall: Run an array of functions in series.
  298. workerize: Move a stand-alone function to a worker thread.
  299. wrap: Wrap the function inside a wrapper function, passing it as the first argument.
  300. zip: Merge together the values of each of the arrays with the values at the corresponding position.
    原文作者:工具
    原文地址: https://segmentfault.com/a/1190000014747781
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞