媒介
在營業開闢過程當中,我們經常會重複運用日期格式化、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 檢察。
- $: jQuery like style dom manipulator.
- $attr: Element attribute manipulation.
- $class: Element class manipulations.
- $css: Element css manipulation.
- [$data](https://eustia.liriliri.io/module.html#dollar-data): Wrapper of $attr, adds data- prefix to keys.
- $event: bind events to certain dom elements.
- $insert: Insert html on different position.
- $offset: Get the position of the element in document.
- $property: Element property html, text, val getter and setter.
- $remove: Remove the set of matched elements from the DOM.
- $safeEls: Convert value into an array, if it’s a string, do querySelector.
- $show: Show elements.
- Blob: Use Blob when available, otherwise BlobBuilder.
- Class: Create JavaScript class.
- Color: Color converter.
- Dispatcher: Flux dispatcher.
- Emitter: Event emitter class which provides observer pattern.
- Enum: Enum type implementation.
- JsonTransformer: Json to json transformer.
- LinkedList: Doubly-linked list implementation.
- LocalStore: LocalStorage wrapper.
- Logger: Simple logger with level filter.
- MutationObserver: Safe MutationObserver, does nothing if MutationObserver is not supported.
- Promise: Lightweight Promise implementation.
- Queue: Queue data structure.
- ReduceStore: Simplified redux like state container.
- Select: Simple wrapper of querySelectorAll to make dom selection easier.
- SessionStore: SessionStorage wrapper.
- Stack: Stack data structure.
- State: Simple state machine.
- Store: Memory storage.
- Tween: Tween engine for JavaScript animations.
- Url: Simple url manipulator.
- Validator: Object values validation.
- abbrev: Calculate the set of unique abbreviations for a given set of strings.
- after: Create a function that invokes once it’s called n or more times.
- ajax: Perform an asynchronous HTTP request.
- allKeys: Retrieve all the names of object’s own and inherited properties.
- arrToMap: Make an object map using array of strings.
- atob: Use Buffer to emulate atob when running in node.
- average: Get average value of given numbers.
- base64: Basic base64 encoding and decoding.
- before: Create a function that invokes less than n times.
- bind: Create a function bound to a given object.
- btoa: Use Buffer to emulate btoa when running in node.
- bubbleSort: Bubble sort implementation.
- callbackify: Convert a function that returns a Promise to a function following the error-first callback style.
- camelCase: Convert string to “camelCase”.
- capitalize: Convert the first character to upper case and the remaining to lower case.
- castPath: Cast value into a property path array.
- centerAlign: Center align text in a string.
- char: Return string representing a character whose Unicode code point is the given integer.
- chunk: Split array into groups the length of given size.
- clamp: Clamp number within the inclusive lower and upper bounds.
- className: Utility for conditionally joining class names.
- clone: Create a shallow-copied clone of the provided plain object.
- cloneDeep: Recursively clone value.
- cmpVersion: Compare version strings.
- compact: Return a copy of the array with all falsy values removed.
- compose: Compose a list of functions.
- compressImg: Compress image using canvas.
- concat: Concat multiple arrays into a single array.
- contain: Check if the value is present in the list.
- convertBase: Convert base of a number.
- cookie: Simple api for handling browser cookies.
- copy: Copy text to clipboard using document.execCommand.
- createAssigner: Used to create extend, extendOwn and defaults.
- createUrl: CreateObjectURL wrapper.
- cssSupports: Check if browser supports a given CSS feature.
- curry: Function currying.
- dateFormat: Simple but extremely useful date format function.
- debounce: Return a new debounced version of the passed function.
- debug: A tiny JavaScript debugging utility.
- decodeUriComponent: Better decodeURIComponent that does not throw if input is invalid.
- defaults: Fill in undefined properties in object with the first value present in the following list of defaults objects.
- define: Define a module, should be used along with use.
- defineProp: Shortcut for Object.defineProperty(defineProperties).
- delay: Invoke function after certain milliseconds.
- delegate: Event delegation.
- detectBrowser: Detect browser info using ua.
- detectOs: Detect operating system using ua.
- difference: Create an array of unique array values not included in the other given array.
- dotCase: Convert string to “dotCase”.
- download: Trigger a file download on client side.
- each: Iterate over elements of collection and invokes iteratee for each element.
- easing: Easing functions adapted from http://jqueryui.com/
- endWith: Check if string ends with the given target string.
- escape: Escapes a string for insertion into HTML, replacing &, <, >, “, `, and ‘ characters.
- escapeJsStr: Escape string to be a valid JavaScript string literal between quotes.
- escapeRegExp: Escape special chars to be used as literals in RegExp constructors.
- evalCss: Load css into page.
- evalJs: Execute js in given context.
- every: Check if predicate return truthy for all elements.
- extend: Copy all of the properties in the source objects over to the destination object.
- extendDeep: Recursive object extending.
- extendOwn: Like extend, but only copies own properties over to the destination object.
- extractBlockCmts: Extract block comments from source code.
- extractUrls: Extract urls from plain text.
- fetch: Turn XMLHttpRequest into promise like.
- fibonacci: Calculate fibonacci number.
- fileSize: Turn bytes into human readable file size.
- fill: Fill elements of array with value.
- filter: Iterates over elements of collection, returning an array of all the values that pass a truth test.
- find: Find the first value that passes a truth test in a collection.
- findIdx: Return the first index where the predicate truth test passes.
- findKey: Return the first key where the predicate truth test passes.
- findLastIdx: Return the last index where the predicate truth test passes.
- flatten: Recursively flatten an array.
- fnParams: Get a function parameter’s names.
- format: Format string in a printf-like format.
- fraction: Convert number to fraction.
- freeze: Shortcut for Object.freeze.
- freezeDeep: Recursively use Object.freeze.
- gcd: Compute the greatest common divisor using Euclid’s algorithm.
- getUrlParam: Get url param.
- has: Checks if key is a direct property.
- hotkey: Capture keyboard input to trigger given events.
- hslToRgb: Convert hsl to rgb.
- identity: Return the first argument given.
- idxOf: Get the index at which the first occurrence of value.
- indent: Indent each line in a string.
- inherits: Inherit the prototype methods from one constructor into another.
- insertionSort: Insertion sort implementation.
- intersect: Compute the list of values that are the intersection of all the arrays.
- intersectRange: Intersect two ranges.
- invert: Create an object composed of the inverted keys and values of object.
- isAbsoluteUrl: Check if an url is absolute.
- isArgs: Check if value is classified as an arguments object.
- isArr: Check if value is an
Array
object. - isArrBuffer: Check if value is an ArrayBuffer.
- isArrLike: Check if value is array-like.
- isBlob: Check if value is a Blob.
- isBool: Check if value is a boolean primitive.
- isBrowser: Check if running in a browser.
- isBuffer: Check if value is a buffer.
- isClose: Check if values are close(almost equal) to each other.
- isDataUrl: Check if a string is a valid data url.
- isDate: Check if value is classified as a Date object.
- isEl: Check if value is a DOM element.
- isEmail: Loosely validate an email address.
- isEmpty: Check if value is an empty object or array.
- isEqual: Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.
- isErr: Check if value is an error.
- isEven: Check if number is even.
- isFile: Check if value is a file.
- isFinite: Check if value is a finite primitive number.
- isFn: Check if value is a function.
- isGeneratorFn: Check if value is a generator function.
- isInt: Checks if value is classified as a Integer.
- isJson: Check if value is a valid JSON.
- isLeapYear: Check if a year is a leap year.
- isMatch: Check if keys and values in src are contained in obj.
- isMiniProgram: Check if running in wechat mini program.
- isMobile: Check whether client is using a mobile browser using ua.
- isNaN: Check if value is an NaN.
- isNative: Check if value is a native function.
- isNil: Check if value is null or undefined, the same as value == null.
- isNode: Check if running in node.
- isNull: Check if value is an Null.
- isNum: Check if value is classified as a Number primitive or object.
- isNumeric: Check if value is numeric.
- isObj: Check if value is the language type of Object.
- isOdd: Check if number is odd.
- isPlainObj: Check if value is an object created by Object constructor.
- isPrimitive: Check if value is string, number, boolean or null.
- isPromise: Check if value looks like a promise.
- isRegExp: Check if value is a regular expression.
- isRelative: Check if path appears to be relative.
- isRetina: Determine if running on a high DPR device or not.
- isStr: Check if value is a string primitive.
- isStream: Check if value is a Node.js stream.
- isTypedArr: Check if value is a typed array.
- isUndef: Check if value is undefined.
- isUrl: Loosely validate an url.
- isWindows: Check if platform is windows.
- jsonp: A simple jsonp implementation.
- kebabCase: Convert string to “kebabCase”.
- keyCode: Key codes and key names conversion.
- keys: Create an array of the own enumerable property names of object.
- last: Get the last element of array.
- lazyRequire: Require modules lazily.
- linkify: Hyperlink urls in a string.
- loadCss: Inject link tag into page with given href value.
- loadImg: Load image with given src.
- loadJs: Inject script tag into page with given src value.
- longest: Get the longest item in an array.
- lowerCase: Convert string to lower case.
- lpad: Pad string on the left side if it’s shorter than length.
- ltrim: Remove chars or white-spaces from beginning of string.
- map: Create an array of values by running each element in collection through iteratee.
- mapObj: Map for objects.
- matcher: Return a predicate function that checks if attrs are contained in an object.
- max: Get maximum value of given numbers.
- memStorage: Memory-backed implementation of the Web Storage API.
- memoize: Memoize a given function by caching the computed result.
- meta: Document meta manipulation, turn name and content into key value pairs.
- methods: Return a sorted list of the names of every method in an object.
- min: Get minimum value of given numbers.
- mkdir: Recursively create directories.
- moment: Tiny moment.js like implementation.
- ms: Convert time string formats to milliseconds.
- negate: Create a function that negates the result of the predicate function.
- nextTick: Next tick for both node and browser.
- noop: A no-operation function.
- normalizePath: Normalize file path slashes.
- now: Gets the number of milliseconds that have elapsed since the Unix epoch.
- objToStr: Alias of Object.prototype.toString.
- omit: Opposite of pick.
- once: Create a function that invokes once.
- optimizeCb: Used for function context binding.
- orientation: Screen orientation helper.
- pad: Pad string on the left and right sides if it’s shorter than length.
- pairs: Convert an object into a list of [key, value] pairs.
- parallel: Run an array of functions in parallel.
- parseArgs: Parse command line argument options, the same as minimist.
- partial: Partially apply a function by filling in given arguments.
- pascalCase: Convert string to “pascalCase”.
- perfNow: High resolution time up to microsecond precision.
- pick: Return a filtered copy of an object.
- pluck: Extract a list of property values.
- precision: Find decimal precision of a given number.
- prefix: Add vendor prefixes to a CSS attribute.
- promisify: Convert callback based functions into Promises.
- property: Return a function that will itself return the key property of any passed-in object.
- query: Parse and stringify url query strings.
- raf: Shortcut for requestAnimationFrame.
- random: Produces a random number between min and max(inclusive).
- randomBytes: Random bytes generator.
- range: Create flexibly-numbered lists of integers.
- ready: Invoke callback when dom is ready, similar to jQuery ready.
- reduce: Turn a list of values into a single value.
- reject: Opposite of filter.
- remove: Remove all elements from array that predicate returns truthy for and return an array of the removed elements.
- repeat: Repeat string n-times.
- restArgs: This accumulates the arguments passed into an array, after a given index.
- rgbToHsl: Convert rgb to hsl.
- rmCookie: Loop through all possible path and domain to remove cookie.
- rmdir: Recursively remove directories.
- root: Root object reference,
global
in nodeJs,window
in browser. - rpad: Pad string on the right side if it’s shorter than length.
- rtrim: Remove chars or white-spaces from end of string.
- safeCb: Create callback based on input value.
- safeDel: Delete object property.
- safeGet: Get object property, don’t throw undefined error.
- safeSet: Set value at path of object.
- safeStorage: Use storage safely in safari private browsing and older browsers.
- sample: Sample random values from a collection.
- scrollTo: Scroll to a target with animation.
- selectionSort: Selection sort implementation.
- shuffle: Randomize the order of the elements in a given array.
- size: Get size of object, length of array like object or the number of keys.
- slice: Create slice of source array or array-like object.
- snakeCase: Convert string to “snakeCase”.
- some: Check if predicate return truthy for any element.
- spaceCase: Convert string to “spaceCase”.
- splitCase: Split different string case to an array.
- splitPath: Split path into device, dir, name and ext.
- startWith: Check if string starts with the given target string.
- strHash: String hash function using djb2.
- stringify: JSON stringify with support for circular object, function etc.
- stripAnsi: Strip ansi codes from a string.
- stripCmt: Strip comments from source code.
- stripColor: Strip ansi color codes from a string.
- stripHtmlTag: Strip html tags from a string.
- sum: Compute sum of given numbers.
- template: Compile JavaScript template into function that can be evaluated for rendering.
- throttle: Return a new throttled version of the passed function.
- through: Tiny wrapper of stream Transform.
- timeAgo: Format datetime with * time ago statement.
- timeTaken: Get execution time of a function.
- toArr: Convert value to an array.
- toBool: Convert value to a boolean.
- toDate: Convert value to a Date.
- toEl: Convert html string to dom elements.
- toInt: Convert value to an integer.
- toNum: Convert value to a number.
- toSrc: Convert function to its source code.
- toStr: Convert value to a string.
- topoSort: Topological sorting algorithm.
- trigger: Trigger browser events.
- trim: Remove chars or white-spaces from beginning end of string.
- tryIt: Run function in a try catch.
- type: Determine the internal JavaScript [[Class]] of an object.
- ucs2: UCS-2 encoding and decoding.
- unescape: Convert HTML entities back, the inverse of escape.
- union: Create an array of unique values, in order, from all given arrays.
- uniqId: Generate a globally-unique id.
- unique: Create duplicate-free version of an array.
- unzip: Opposite of zip.
- upperCase: Convert string to upper case.
- upperFirst: Convert the first character of string to upper case.
- use: Use modules that is created by define.
- utf8: UTF-8 encoding and decoding.
- uuid: RFC4122 version 4 compliant uuid generator.
- values: Create an array of the own enumerable property values of object.
- viewportScale: Get viewport scale.
- waterfall: Run an array of functions in series.
- workerize: Move a stand-alone function to a worker thread.
- wrap: Wrap the function inside a wrapper function, passing it as the first argument.
- zip: Merge together the values of each of the arrays with the values at the corresponding position.