diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 1ba56d6b..f6a4228a 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -9,3 +9,10 @@ updates: directory: / # Location of package manifests schedule: interval: weekly + open-pull-requests-limit: 5 + ignore: + - dependency-name: 'aws*' + - dependency-name: typescript + versions: [4.x] + - dependency-name: '*' + update-types: ['version-update:semver-patch'] diff --git a/CHANGELOG.md b/CHANGELOG.md index cb588744..3d3a1ae6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Change logs +## 2023.05.20 v4.1.0 + +1. use `load-source` `mount-css` `mount-image` `mount-script` `mount-style` +2. some translate work + ## 2023.05.18 v4.0.0 1. split `csv` into `arrayToCSV` `CSVToArray` `CSVToJSON` `JSONToCSV` diff --git a/README-zh_CN.md b/README-zh_CN.md new file mode 100755 index 00000000..4e922bf6 --- /dev/null +++ b/README-zh_CN.md @@ -0,0 +1,180 @@ +
+ +# js-cool + +这是一个纯原生 ES6 开发的 Javascript 常用方法库 + +[![NPM version][npm-image]][npm-url] +[![Codacy Badge][codacy-image]][codacy-url] +[![build status][travis-image]][travis-url] +[![Test coverage][codecov-image]][codecov-url] +[![npm download][download-image]][download-url] +[![gzip][gzip-image]][gzip-url] +[![License][license-image]][license-url] + +[![Sonar][sonar-image]][sonar-url] + +
+ +
+ +### **[Documentation](https://www.saqqdy.com/js-cool)** • **[Change Log](./CHANGELOG.md)** + +**使用其他语言阅读:[English](./README.md) | 简体中文** + +
+ +## 安装 + +```bash +# 通过npm安装 +npm install --save js-cool + +# 或者通过yarn安装 +yarn add js-cool + +# 或者通过pnpm安装 +pnpm install js-cool +``` + +## 使用 + +### 通过 import 引入模块的方式 + +```js +// 在你的.vue或者main.js里面写上import +import { getOsVersion, trim } from 'js-cool' +// 使用 +trim(somestring, type) // 返回清理空格后的字符串 +getOsVersion() // 返回系统版本 +// ... +``` + +### 使用文件引入的方式 + +1. 通过 require 引入 + + ```js + // 在你的main.js文件里面加上下面这一行 + const { getOsVersion } = require('js-cool') + ``` + +2. html 静态页直接使用 + + ```html + + + ``` + +## 所有方法汇总 + +```js +const functionList = { + // 全局参数 + client, // client方法返回一个浏览器判断结果对象 + pattern, // pattern返回一些常用的正则 + // String扩展、数组方法 + trim, // 根据传参来去除空格 + clearAttr, // 去除HTML标签所有属性 + clearHtml, // 去除HTML标签 + getNumber, // 获取字符串中的数字 + camel2Dash, // 将驼峰字符串转成-间隔且全小写的Dash模式 + dash2Camel, // 将-间隔且全小写的Dash模式转成驼峰字符串 + getRandomNum, // 获取随机整数 + getRandomStr, // 获取随机字符串 + getRandomStrWidthSpecialChar, // 获取随机字符串带特殊符号 + getCHSLength, // 获取字符串长度,中文算2个字符 + cutCHSString, // 截取字符串,中文算2个字节 + textareaInsertText, // textarea或input对象在指定的光标位置插入文字 + textareaMoveToEnd, // textarea或input对象将光标定位到文字尾部 + // 获取一下状态 + isDigitals, // 是否为由数字组成的字符串 + isExitsFunction, // 是否存在指定函数 + isExitsVariable, // 是否存在指定变量 + windowSize, // windowSize获取窗口大小 + getAppVersion, // 获取APP版本号 + getOsVersion, // 获取手机系统版本 + getIsAppVersionLastest, // 版本号大小对比 + getDirParam, // 获取目录形式URL参数 + getParameter, // 获取单个URL参数 + getUrlParam, // 获取URL参数 + // 缓存、cookie、session + getCache, // 读取localStorage + setCache, // 写入localStorage + delCache, // 删除localStorage + getSession, // 读取sessionStorage + setSession, // 写入sessionStorage + delSession, // 删除sessionStorage + getCookie, // 读取cookie + setCookie, // 写入cookie + delCookie, // 删除cookie + // 编码与解码 + encodeBase64, // 字符串、数字转base64 + encodeUtf8, // 编码Utf8 + decodeBase64, // base64解码 + decodeUtf8, // 解码Utf8 + // 事件委托、其他事件方法 + stopBubble, // 阻止冒泡 + stopDefault, // 阻止默认事件 + addEvent, // 事件委托,支持多次委托 + removeEvent, // removeEvent移除由addEvent创建的事件委托 + getScrollPosition, // 获取滑动到顶部和底部 返回'top' 'bottom',建议使用限流 + // 工具类 + nextIndex, // 返回下一个zIndex值 + fixNumber, // 截取小数点后几位,不足的不补0 + extend, // 深拷贝 + delay, // 防抖节流 + getType, // 获取目标类型 + isArray, // 判断是否数组 + cleanData, // 清洗数据 + download, // 文件下载 + searchTreeObject, // 对象查找 + openUrl, // 新标签页打开链接(浏览器不能解析的文件跳转下载) + toThousands, // 千分位分割方法 + all, // 如果所提供的谓词函数对一个集合中的所有元素都返回true,则返回true,否则返回false。 + any, // 如果所提供的谓词函数对一个集合中的至少一个元素返回true,则返回true,否则返回false。 + uuid, // 浏览器端生成uuid,采用v4方法 + CSVToArray, // csv与json、array相互转换 + arrayToCSV, // csv与json、array相互转换 + CSVToJSON, // csv与json、array相互转换 + JSONToCSV, // csv与json、array相互转换 + RGBToHex, // 将RGB组件的值转换为颜色代码。 + intersect, // 多个数组求交集 + union, // 求多个数组的并集 + minus, // 求多个数组的差集,属于A但不属于B/C/D...的元素 + complement, // 多个数组求补集 + contains, // 数组是否包含指定元素 + unique, // 数组去重 + fillIPv6, // ipv6地址补全 + getProperty, // 根据路径字符串获取数组、对象属性值 + setProperty, // 根据路径字符串设置数组、对象属性值 + loadSource, // 动态加载资源,支持js、图片、css链接、css样式字符串 + mountCss, // 动态加载css链接资源 + mountImg, // 动态加载图片资源 + mountJs, // 动态加载js链接资源 + mountStyle // 动态加载css样式 +} +``` + +## 问题和支持 + +请提交一个 issue [here](https://github.com/saqqdy/js-cool/issues). + +## License + +[npm-image]: https://img.shields.io/npm/v/js-cool.svg?style=flat-square +[npm-url]: https://npmjs.org/package/js-cool +[codacy-image]: https://app.codacy.com/project/badge/Grade/f70d4880e4ad4f40aa970eb9ee9d0696 +[codacy-url]: https://www.codacy.com/gh/saqqdy/js-cool/dashboard?utm_source=github.com&utm_medium=referral&utm_content=saqqdy/js-cool&utm_campaign=Badge_Grade +[travis-image]: https://travis-ci.com/saqqdy/js-cool.svg?branch=master +[travis-url]: https://travis-ci.com/saqqdy/js-cool +[codecov-image]: https://img.shields.io/codecov/c/github/saqqdy/js-cool.svg?style=flat-square +[codecov-url]: https://codecov.io/github/saqqdy/js-cool?branch=master +[download-image]: https://img.shields.io/npm/dm/js-cool.svg?style=flat-square +[download-url]: https://npmjs.org/package/js-cool +[gzip-image]: http://img.badgesize.io/https://unpkg.com/js-cool/dist/js-cool.global.prod.js?compression=gzip&label=gzip%20size:%20JS +[gzip-url]: http://img.badgesize.io/https://unpkg.com/js-cool/dist/js-cool.global.prod.js?compression=gzip&label=gzip%20size:%20JS +[license-image]: https://img.shields.io/badge/License-MIT-blue.svg +[license-url]: LICENSE +[sonar-image]: https://sonarcloud.io/api/project_badges/quality_gate?project=saqqdy_js-cool +[sonar-url]: https://sonarcloud.io/dashboard?id=saqqdy_js-cool diff --git a/README.md b/README.md index 815c1750..9d18c772 100755 --- a/README.md +++ b/README.md @@ -2,15 +2,7 @@ # js-cool - - -
- -这是一个纯原生 ES6 开发的 Javascript 常用方法库 - -
- -
+This is a pure native js front-end common method library [![NPM version][npm-image]][npm-url] [![Codacy Badge][codacy-image]][codacy-url] @@ -28,146 +20,149 @@ ### **[Documentation](https://www.saqqdy.com/js-cool)** • **[Change Log](./CHANGELOG.md)** +**Read this in other languages: English | [简体中文](./README-zh_CN.md)** +
-## 安装 +## Installation -```shell -# 通过npm安装 +```bash +## Install via npm npm install --save js-cool -# 或者通过yarn安装 +# Or install via yarn yarn add js-cool -# 或者通过pnpm安装 +# or install via pnpm pnpm install js-cool ``` -## 使用 +## Use -### 通过 import 引入模块的方式 +### Introducing modules via import ```js -// 在你的.vue或者main.js里面写上import +// Write import inside your .vue or main.js import { getOsVersion, trim } from 'js-cool' -// 使用 -trim(somestring, type) // 返回清理空格后的字符串 -getOsVersion() // 返回系统版本 +// Use +trim(somestring, type) // return the string after cleaning up the spaces +getOsVersion() // return the system version // ... ``` -### 使用文件引入的方式 +### Ways to introduce using files -1. 通过 require 引入 +1. Introduce via require ```js - // 在你的main.js文件里面加上下面这一行 + // Add the following line to your main.js file const { getOsVersion } = require('js-cool') ``` -2. html 静态页直接使用 +2. html Static pages are used directly ```html - + ``` -## 所有方法汇总 +## Summary of all methods ```js const functionList = { - // 全局参数 - client, // client方法返回一个浏览器判断结果对象 - pattern, // pattern返回一些常用的正则 - // String扩展、数组方法 - trim, // 根据传参来去除空格 - clearAttr, // 去除HTML标签所有属性 - clearHtml, // 去除HTML标签 - getNumber, // 获取字符串中的数字 - camel2Dash, // 将驼峰字符串转成-间隔且全小写的Dash模式 - dash2Camel, // 将-间隔且全小写的Dash模式转成驼峰字符串 - getRandomNum, // 获取随机整数 - getRandomStr, // 获取随机字符串 - getRandomStrWidthSpecialChar, // 获取随机字符串带特殊符号 - getCHSLength, // 获取字符串长度,中文算2个字符 - cutCHSString, // 截取字符串,中文算2个字节 - textareaInsertText, // textarea或input对象在指定的光标位置插入文字 - textareaMoveToEnd, // textarea或input对象将光标定位到文字尾部 - // 获取一下状态 - isDigitals, // 是否为由数字组成的字符串 - isExitsFunction, // 是否存在指定函数 - isExitsVariable, // 是否存在指定变量 - windowSize, // windowSize获取窗口大小 - getAppVersion, // 获取APP版本号 - getOsVersion, // 获取手机系统版本 - getIsAppVersionLastest, // 版本号大小对比 - getDirParam, // 获取目录形式URL参数 - getParameter, // 获取单个URL参数 - getUrlParam, // 获取URL参数 - // 缓存、cookie、session - getCache, // 读取localStorage - setCache, // 写入localStorage - delCache, // 删除localStorage - getSession, // 读取sessionStorage - setSession, // 写入sessionStorage - delSession, // 删除sessionStorage - getCookie, // 读取cookie - setCookie, // 写入cookie - delCookie, // 删除cookie - // 编码与解码 - encodeBase64, // 字符串、数字转base64 - encodeUtf8, // 编码Utf8 - decodeBase64, // base64解码 - decodeUtf8, // 解码Utf8 - // 事件委托、其他事件方法 - stopBubble, // 阻止冒泡 - stopDefault, // 阻止默认事件 - addEvent, // 事件委托,支持多次委托 - removeEvent, // removeEvent移除由addEvent创建的事件委托 - getScrollPosition, // 获取滑动到顶部和底部 返回'top' 'bottom',建议使用限流 - // 工具类 - nextIndex, // 返回下一个zIndex值 - fixNumber, // 截取小数点后几位,不足的不补0 - extend, // 深拷贝 - delay, // 防抖节流 - getType, // 获取目标类型 - isArray, // 判断是否数组 - cleanData, // 清洗数据 - download, // 文件下载 - searchTreeObject, // 对象查找 - openUrl, // 新标签页打开链接(浏览器不能解析的文件跳转下载) - toThousands, // 千分位分割方法 - all, // 如果所提供的谓词函数对一个集合中的所有元素都返回true,则返回true,否则返回false。 - any, // 如果所提供的谓词函数对一个集合中的至少一个元素返回true,则返回true,否则返回false。 - uuid, // 浏览器端生成uuid,采用v4方法 - CSVToArray, // csv与json、array相互转换 - arrayToCSV, // csv与json、array相互转换 - CSVToJSON, // csv与json、array相互转换 - JSONToCSV, // csv与json、array相互转换 - RGBToHex, // 将RGB组件的值转换为颜色代码。 - intersect, // 多个数组求交集 - union, // 求多个数组的并集 - minus, // 求多个数组的差集,属于A但不属于B/C/D...的元素 - complement, // 多个数组求补集 - contains, // 数组是否包含指定元素 - unique, // 数组去重 - fillIPv6, // ipv6地址补全 - getProperty, // 根据路径字符串获取数组、对象属性值 - setProperty, // 根据路径字符串设置数组、对象属性值 - loadSource, // 动态加载资源,支持js、图片、css链接、css样式字符串 - mountCss, // 动态加载css链接资源 - mountImg, // 动态加载图片资源 - mountJs, // 动态加载js链接资源 - mountStyle // 动态加载css样式 + // global parameters + client, // the client method returns a browser result object + pattern, // pattern returns some common rules + // String extensions, array methods + trim, // removes spaces based on the passed parameters + clearAttr, // remove all attributes of HTML tags + clearHtml, // remove HTML tags + getNumber, // Get the number in the string + camel2Dash, // convert a humped string to -spaced and all lowercase dash mode + dash2Camel, // convert -spaced all-lowercase dash pattern to camel string + getRandomNum, // Get a random integer + getRandomStr, // get a random string + getRandomStrWidthSpecialChar, // get a random string with special symbols + getCHSLength, // get the length of the string, Chinese counts as 2 characters + cutCHSString, // get the string, Chinese count as 2 bytes + textareaInsertText, // textarea or input object to insert text at the specified cursor position + textareaMoveToEnd, // textarea or input object to position the cursor to the end of the text + // Get a status + isDigitals, // whether it is a string composed of numbers + isExitsFunction, // if the specified function exists + isExitsVariable, // if the specified variable exists + windowSize, // windowSize to get the window size + getAppVersion, // Get the app version number + getOsVersion, // get the system version of the phone + getIsAppVersionLastest, // compare the version number size + getDirParam, // get the URL parameter in the form of a directory + getParameter, // Get a single URL parameter + getUrlParam, // Get URL parameters + // cache, cookie, session + getCache, // read localStorage + setCache, // write to localStorage + delCache, // delete localStorage + getSession, // read sessionStorage + setSession, // write to sessionStorage + delSession, // delete sessionStorage + getCookie, // read cookie + setCookie, // write a cookie + delCookie, // delete a cookie + // Encode and decode + encodeBase64, // convert strings, numbers to base64 + encodeUtf8, // encode Utf8 + decodeBase64, // base64 decode + decodeUtf8, // decode Utf8 + // event delegate, other event methods + stopBubble, // stop bubbling + stopDefault, // stop default events + addEvent, // event delegate, support multiple delegates + removeEvent, // removeEvent removes the event delegate created by addEvent + getScrollPosition, // get scroll to top and bottom return 'top' 'bottom', recommend using flow limit + // tool class + nextIndex, // return the next zIndex value + fixNumber, // truncate a few decimal places, not 0 for shortage + extend, // deep copy + delay, // anti-dither throttling + getType, // get the target type + isArray, // Determine if it is an array + cleanData, // clean data + download, // file download + searchTreeObject, // find object + openUrl, // open link in a new tab (file jump download if browser can't parse) + toThousands, // Thousands division method + all, // return true if the provided predicate function returns true for all elements in a set, otherwise return false. + any, // Returns true if the provided predicate function returns true for at least one element of a set, false otherwise. + uuid, // generate uuid on browser side, use v4 method + CSVToArray, // csv to json, array conversion + arrayToCSV, // convert csv to json, array + CSVToJSON, // csv to json, array conversion + JSONToCSV, // csv to json, array conversion + RGBToHex, // Convert RGB component values to color codes. + intersect, // find intersection of multiple arrays + union, // find the union of multiple arrays + minus, // find the difference of multiple arrays, which belong to A but not B/C/D... elements of + complement, // find the complement of multiple arrays + contains, // whether the array contains the specified element + unique, // array de-duplication + fillIPv6, // ipv6 address completion + getProperty, // Get array, object property values based on path string + setProperty, // set array, object property values based on path string + loadSource, // load resources dynamically, support js, images, css links, css style strings + mountCss, // dynamically load css link resources + mountImg, // load image resource dynamically + mountJs, // load js link resources dynamically + mountStyle // load css styles dynamically } ``` -## 参与贡献 +## Support & Issues + +Please open an issue [here](https://github.com/saqqdy/js-cool/issues). + +## License -1. fork 本仓库 -2. 新建 feature_xxx 分支 -3. 提交代码 -4. 新建 pull request +[MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/js-cool.svg?style=flat-square [npm-url]: https://npmjs.org/package/js-cool diff --git a/build/rollup.config.ts b/build/rollup.config.ts index 9db2ad85..9f2457b4 100644 --- a/build/rollup.config.ts +++ b/build/rollup.config.ts @@ -112,7 +112,14 @@ function createEntry(config: Config) { } if (!isGlobalBuild) { - _config.external.push('core-js') + _config.external.push( + 'core-js', + 'mount-css', + 'mount-script', + 'mount-image', + 'mount-style', + 'load-source' + ) } _config.plugins.push( diff --git a/package.json b/package.json index a94f56b1..237417db 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "js-cool", - "description": "这是一个纯原生ES6开发的Javascript常用方法库", - "version": "4.0.0", + "description": "This is a pure native js front-end common method library", + "version": "4.1.0", "packageManager": "pnpm@8.5.1", "main": "dist/js-cool.cjs.js", "module": "dist/js-cool.esm-bundler.js", @@ -49,7 +49,13 @@ "prettier": "prettier --write \"**/*.{js,ts,jsx,tsx,yml,json,md}\"", "pub.bak": "git add . && git commit -m $npm_package_version && git pull && git push" }, - "dependencies": {}, + "dependencies": { + "load-source": "^1.0.0", + "mount-css": "^1.0.0", + "mount-image": "^1.0.0", + "mount-script": "^1.0.0", + "mount-style": "^1.0.0" + }, "devDependencies": { "@babel/core": "^7.21.8", "@babel/plugin-transform-runtime": "^7.21.4", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 82b0f1c9..7c7a5c4f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1,5 +1,22 @@ lockfileVersion: '6.0' +dependencies: + load-source: + specifier: ^1.0.0 + version: 1.0.0(core-js@3.30.2) + mount-css: + specifier: ^1.0.0 + version: 1.0.0(core-js@3.30.2) + mount-image: + specifier: ^1.0.0 + version: 1.0.0(core-js@3.30.2) + mount-script: + specifier: ^1.0.0 + version: 1.0.0(core-js@3.30.2) + mount-style: + specifier: ^1.0.0 + version: 1.0.0(core-js@3.30.2) + devDependencies: '@babel/core': specifier: ^7.21.8 @@ -1385,7 +1402,7 @@ packages: /@eslint-sets/eslint-config-basic@5.2.0(@babel/core@7.21.8)(@typescript-eslint/parser@5.59.6)(eslint@8.40.0)(prettier@2.8.8)(typescript@5.0.4): resolution: {integrity: sha512-iIVWKZ9T5lpEGkJTa/VcDt5/zymoaMqmvPD/nz1evW0Gjji0ojpCJgdQwJ7fVYSEhRayHo+TtF/heo3ErKucTg==} peerDependencies: - eslint: '>=7.4.0 || >= 8.0.0 || ^8.0.0' + eslint: '>=7.4.0 || ^8.0.0' prettier: '>=2.0.0' typescript: '*' peerDependenciesMeta: @@ -2799,7 +2816,6 @@ packages: /core-js@3.30.2: resolution: {integrity: sha512-uBJiDmwqsbJCWHAwjrx3cvjbMXP7xD72Dmsn5LOJpiRmE3WbBbN5rCqQ2Qh6Ek6/eOrjlWngEynBWo4VxerQhg==} requiresBuild: true - dev: true /cosmiconfig@8.1.3: resolution: {integrity: sha512-/UkO2JKI18b5jVMJUp0lvKFMpa/Gye+ZgZjKD+DGEN9y7NRcf/nK1A0sp67ONmKtnDCNMS44E6jrk0Yc3bDuUw==} @@ -4569,6 +4585,19 @@ packages: strip-bom: 3.0.0 dev: true + /load-source@1.0.0(core-js@3.30.2): + resolution: {integrity: sha512-+beTMZM7UF0tiL532bit98ehiaJJLBkpr37piRRkUiWJsdIEvInNf/Wy+vBtQefA4PNZlWZ7oTzXbH++80DUHg==} + engines: {node: '>=12.20'} + peerDependencies: + core-js: '>= 3' + dependencies: + core-js: 3.30.2 + mount-css: 1.0.0(core-js@3.30.2) + mount-image: 1.0.0(core-js@3.30.2) + mount-script: 1.0.0(core-js@3.30.2) + mount-style: 1.0.0(core-js@3.30.2) + dev: false + /load-yml@1.3.0(core-js@3.30.2): resolution: {integrity: sha512-LkbCmVZULVsMADpXe3WIvM8GfsTDDbbnItNaEJIhoJeyab359GyQ5dM4esqyE+XH60Yo8xB5N2SeEk174RY6Rg==} engines: {node: '>=12.20'} @@ -4899,6 +4928,42 @@ packages: workspace-root: 2.5.1 dev: true + /mount-css@1.0.0(core-js@3.30.2): + resolution: {integrity: sha512-CyGaRpOUibuZWKSeB1mtPBg1Uze+FDn0z4EviEXfkd3DDbDlXFvQAzLhW4OMHZzwgwxm84cm5Rgw/7/6FOl1Sw==} + engines: {node: '>=12.20'} + peerDependencies: + core-js: '>= 3' + dependencies: + core-js: 3.30.2 + dev: false + + /mount-image@1.0.0(core-js@3.30.2): + resolution: {integrity: sha512-P0e7bubiAWb9Vn2ECFF1HMlPERKmA+JmI57toTsau6TaEs547/Ihp7VdDRigmbjCfEVtaRpc/4Bg4J27jOgUxQ==} + engines: {node: '>=12.20'} + peerDependencies: + core-js: '>= 3' + dependencies: + core-js: 3.30.2 + dev: false + + /mount-script@1.0.0(core-js@3.30.2): + resolution: {integrity: sha512-VzYm1/IOtj9nIclRX2xjcAQHzsaMz5bJI10mZ/RDRzvQkHIcj9U+S4idzwFVJD5ttQkoff+f/SF6fMVcysNvZQ==} + engines: {node: '>=12.20'} + peerDependencies: + core-js: '>= 3' + dependencies: + core-js: 3.30.2 + dev: false + + /mount-style@1.0.0(core-js@3.30.2): + resolution: {integrity: sha512-mNsV86HZtsdyQN8NMqFmAOSMr89x/DiccJIVLgaxpV7TssAc+4rEVDMYs8e4fo3lIVV78DldGUFXCbUuSNbIMA==} + engines: {node: '>=12.20'} + peerDependencies: + core-js: '>= 3' + dependencies: + core-js: 3.30.2 + dev: false + /ms@2.1.2: resolution: {integrity: sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==} dev: true diff --git a/scripts/deploy.sh b/scripts/deploy.sh index e1972494..42cba2d9 100644 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -1,26 +1,26 @@ #!/usr/bin/env sh -# 确保脚本抛出遇到的错误 +# Make sure the script throws the error encountered set -e -# 生成静态文件 +# Generate static files pnpm build:docs -# 进入生成的文件夹 +# Go to the generated folder cd docs/ -# 如果是发布到自定义域名 +# If you are publishing to a custom domain # echo 'github.saqqdy.com' > CNAME git init git add . git commit -m 'deploy' -# 如果发布到 https://.github.io +# if publishing to https://.github.io # git push -f git@github.com:/.github.io.git master -# 把上面的 换成你自己的 Github 用户名, 换成仓库名,比如我这里就是: +# Replace with your own Github username and with the repository name, for example, in my case it's git push -f git@github.com:saqqdy/js-cool.git master:gh-pages cd - diff --git a/scripts/version.ts b/scripts/version.ts index 38ab3be1..e6f89020 100644 --- a/scripts/version.ts +++ b/scripts/version.ts @@ -33,10 +33,10 @@ if (argv.length) { shell: process.platform === 'win32' }) } else { - console.info('请输入有效的版本类型') + console.info('Please enter a valid version') process.exit(1) } } else { - console.info('请输入版本类型') + console.info('Please enter the version') process.exit(1) } diff --git a/src/_eval.ts b/src/_eval.ts index 751d9de0..bf427eca 100644 --- a/src/_eval.ts +++ b/src/_eval.ts @@ -1,5 +1,5 @@ /** - * eval替代方法 + * eval alternative method * * return - Function | undefined */ diff --git a/src/any.ts b/src/any.ts index f1b69d03..b1dd37d9 100644 --- a/src/any.ts +++ b/src/any.ts @@ -1,6 +1,6 @@ import type { AnyFunction } from '../typings/common' /** - * 如果所提供的谓词函数对一个集合中的至少一个元素返回true,则返回true,否则返回false。 + * Returns true if the provided predicate function returns true for at least one element of a set, otherwise it returns false. * * @example * ```js @@ -10,9 +10,9 @@ import type { AnyFunction } from '../typings/common' * ```js * any([0, 0, 1, 0]); // true * ``` - * @param arr - 目标数组 - * @param fn - 判断方法 - * @returns 返回判断结果 + * @param arr - the target array + * @param fn - the judgment method + * @returns returns the result of the judgment */ const any = (arr: any[], fn: AnyFunction) => arr.some(fn) diff --git a/src/index.default.ts b/src/index.default.ts index 7d45e297..d316f86f 100644 --- a/src/index.default.ts +++ b/src/index.default.ts @@ -1,4 +1,8 @@ -// export type { AnyObject, AnyFunction, ArrayOneMore } from '../typings/common' +import loadSource from 'load-source' // 动态加载资源,支持js、图片、css链接、css样式字符串 +import mountCss from 'mount-css' // 动态加载css链接资源 +import mountImg from 'mount-image' // 动态加载图片资源 +import mountJs from 'mount-script' // 动态加载js链接资源 +import mountStyle from 'mount-style' // 动态加载css样式 // 全局参数 import client from './client' // client方法返回一个浏览器判断结果对象 @@ -87,14 +91,13 @@ import fillIPv6 from './fillIPv6' // ipv6地址补全 import getProperty from './getProperty' // 根据路径字符串获取数组、对象属性值 import setProperty from './setProperty' // 根据路径字符串设置数组、对象属性值 -import loadSource from './loadSource' // 动态加载资源,支持js、图片、css链接、css样式字符串 -import mountCss from './mountCss' // 动态加载css链接资源 -import mountImg from './mountImg' // 动态加载图片资源 -import mountJs from './mountJs' // 动态加载js链接资源 -import mountStyle from './mountStyle' // 动态加载css样式 - export default { version: '__VERSION__', + loadSource, + mountCss, + mountImg, + mountJs, + mountStyle, RGBToHex, addEvent, all, @@ -150,12 +153,7 @@ export default { isExitsFunction, isExitsVariable, isPlainObject, - loadSource, minus, - mountCss, - mountImg, - mountJs, - mountStyle, nextIndex, openUrl, pattern, diff --git a/src/index.mjs b/src/index.mjs index 5717b4d0..158600d0 100644 --- a/src/index.mjs +++ b/src/index.mjs @@ -2,6 +2,11 @@ import jsCool from './js-cool.cjs.js' const { version, + loadSource, + mountCss, + mountImg, + mountJs, + mountStyle, CSVToArray, CSVToJSON, JSONToCSV, @@ -54,12 +59,7 @@ const { isExitsFunction, isExitsVariable, isPlainObject, - loadSource, minus, - mountCss, - mountImg, - mountJs, - mountStyle, nextIndex, openUrl, pattern, @@ -85,6 +85,11 @@ const { export { jsCool as default, version, + loadSource, + mountCss, + mountImg, + mountJs, + mountStyle, CSVToArray, CSVToJSON, JSONToCSV, @@ -137,12 +142,7 @@ export { isExitsFunction, isExitsVariable, isPlainObject, - loadSource, minus, - mountCss, - mountImg, - mountJs, - mountStyle, nextIndex, openUrl, pattern, diff --git a/src/index.ts b/src/index.ts index 5a565e5a..5c81e690 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,11 @@ export type { AnyObject, AnyFunction, ArrayOneMore } from '../typings/common' +export { default as loadSource } from 'load-source' // 动态加载资源,支持js、图片、css链接、css样式字符串 +export { default as mountCss } from 'mount-css' // 动态加载css链接资源 +export { default as mountImg } from 'mount-image' // 动态加载图片资源 +export { default as mountJs } from 'mount-script' // 动态加载js链接资源 +export { default as mountStyle } from 'mount-style' // 动态加载css样式 + // 全局参数 export { default as client } from './client' // client方法返回一个浏览器判断结果对象 export { default as pattern } from './pattern' // pattern返回一些常用的正则 @@ -87,23 +93,23 @@ export { default as fillIPv6 } from './fillIPv6' // ipv6地址补全 export { default as getProperty } from './getProperty' // 根据路径字符串获取数组、对象属性值 export { default as setProperty } from './setProperty' // 根据路径字符串设置数组、对象属性值 -export { default as loadSource, type SourceFileType, type SourceOptions } from './loadSource' // 动态加载资源,支持js、图片、css链接、css样式字符串 -export { - default as mountCss, - type LinkAttributes, - type HTMLLinkElementEX, - type CssOptions -} from './mountCss' // 动态加载css链接资源 -export { - default as mountImg, - type ImageAttributes, - type HTMLImageElementEX, - type ImgOptions -} from './mountImg' // 动态加载图片资源 -export { - default as mountJs, - type ScriptAttributes, - type HTMLScriptElementEX, - type JsOptions -} from './mountJs' // 动态加载js链接资源 -export { default as mountStyle, type StyleAttributes, type StyleOptions } from './mountStyle' // 动态加载css样式 +// export { default as loadSource, type SourceFileType, type SourceOptions } from './loadSource' // 动态加载资源,支持js、图片、css链接、css样式字符串 +// export { +// default as mountCss, +// type LinkAttributes, +// type HTMLLinkElementEX, +// type CssOptions +// } from './mountCss' // 动态加载css链接资源 +// export { +// default as mountImg, +// type ImageAttributes, +// type HTMLImageElementEX, +// type ImgOptions +// } from './mountImg' // 动态加载图片资源 +// export { +// default as mountJs, +// type ScriptAttributes, +// type HTMLScriptElementEX, +// type JsOptions +// } from './mountJs' // 动态加载js链接资源 +// export { default as mountStyle, type StyleAttributes, type StyleOptions } from './mountStyle' // 动态加载css样式 diff --git a/src/loadSource.ts b/src/loadSource.ts deleted file mode 100644 index 7a68a988..00000000 --- a/src/loadSource.ts +++ /dev/null @@ -1,47 +0,0 @@ -import mountCss, { type CssOptions, type LinkAttributes } from './mountCss' -import mountImg, { type ImageAttributes, type ImgOptions } from './mountImg' -import mountJs, { type JsOptions, type ScriptAttributes } from './mountJs' -import mountStyle, { type StyleAttributes, type StyleOptions } from './mountStyle' - -export type SourceFileType = 'js' | 'img' | 'css' | 'style' | string -export interface SourceOptions { - type: SourceFileType - attrs?: LinkAttributes | StyleAttributes | ScriptAttributes | ImageAttributes - props?: LinkAttributes | StyleAttributes | ScriptAttributes | ImageAttributes - force?: boolean -} - -/** - * 动态加载资源,支持js、图片、css链接、css样式字符串 - * - * @param url - 资源链接,传入styleString时,type必传 - * @param option - 参数: attrs, props, force - * @returns - true|false|imgUrl - */ -async function loadSource( - url: string, - option: SourceFileType | SourceOptions -): Promise { - if (!url) throw new Error('url不能为空') - if (!option) option = {} as SourceOptions - if (typeof option === 'string') { - option = { type: option } - } else if (!option.type) { - const match = /\.(\w+)$/.exec(url) - if (!match || !match[1]) throw new Error('url不合法') - option.type = match[1] - } - option.force ??= false - option.type && (option.type = option.type.toLowerCase()) - if (!['js', 'img', 'css', 'style'].includes(option.type)) - throw new Error(`${option.type}类型暂不支持`) - const func: Record<'js' | 'img' | 'css' | 'style' | string, Function> = { - js: (src: string) => mountJs(src, option as JsOptions), - img: (src: string) => mountImg(src, option as ImgOptions), - css: (src: string) => mountCss(src, option as CssOptions), - style: (css: string) => mountStyle(css, option as StyleOptions) - } - return await func[option.type]?.(url) -} - -export default loadSource diff --git a/src/mountCss.ts b/src/mountCss.ts deleted file mode 100644 index 25932da4..00000000 --- a/src/mountCss.ts +++ /dev/null @@ -1,72 +0,0 @@ -export type LinkAttributes = Pick< - HTMLLinkElement, - | 'as' - | 'charset' - | 'crossOrigin' - | 'disabled' - | 'href' - | 'hreflang' - | 'imageSizes' - | 'imageSrcset' - | 'integrity' - | 'media' - | 'referrerPolicy' - | 'rel' - | 'rev' - | 'target' - | 'type' -> - -export interface HTMLLinkElementEX extends HTMLLinkElement { - onreadystatechange?: any - readyState?: 'loaded' | 'complete' -} - -export interface CssOptions { - attrs?: LinkAttributes - props?: LinkAttributes - force?: boolean -} - -/** - * 动态加载css链接资源 - * - * @param src - 资源地址 - * @param option - 参数: attrs, props, force - * @returns - result - */ -function mountCss(src: string, option: CssOptions): Promise { - if (!src) throw new Error('[mountCss]:url不能为空') - const { attrs, props, force = false } = option - return new Promise((resolve, reject) => { - if (!force && document.querySelector(`link[href="${src}"]`)) { - resolve(true) - return - } - const dom: HTMLLinkElementEX = document.createElement('link') - let attr: keyof LinkAttributes, prop: keyof LinkAttributes - if (attrs) { - for (attr in attrs) { - dom[attr] = attrs[attr] as never - } - } - if (props) { - for (prop in props) { - dom[prop] = props[prop] as never - } - } - dom.rel = 'stylesheet' - dom.type = 'text/css' - dom.href = src - document.getElementsByTagName('head')[0].appendChild(dom) - dom.onload = dom.onreadystatechange = function () { - if (!dom.readyState || ['loaded', 'complete'].includes(dom.readyState)) { - dom.onload = dom.onreadystatechange = null - resolve(true) - } - } - dom.onerror = reject - }) -} - -export default mountCss diff --git a/src/mountImg.ts b/src/mountImg.ts deleted file mode 100644 index ef2a62f9..00000000 --- a/src/mountImg.ts +++ /dev/null @@ -1,74 +0,0 @@ -export type ImageAttributes = Pick< - HTMLImageElement, - | 'align' - | 'alt' - | 'border' - | 'crossOrigin' - | 'decoding' - | 'height' - | 'hspace' - | 'isMap' - | 'loading' - | 'longDesc' - | 'lowsrc' - | 'name' - | 'referrerPolicy' - | 'sizes' - | 'src' - | 'srcset' - | 'useMap' - | 'vspace' - | 'width' -> - -export interface HTMLImageElementEX extends HTMLImageElement { - onreadystatechange?: any - readyState?: 'loaded' | 'complete' -} - -export interface ImgOptions { - attrs?: ImageAttributes - props?: ImageAttributes - force?: boolean -} - -/** - * 动态加载图片资源 - * - * @param src - 资源地址 - * @param option - 参数: attrs, props, force - * @returns - result - */ -function mountImg(src: string, option: ImgOptions): Promise { - if (!src) throw new Error('[mountImg]:url不能为空') - const { attrs, props, force = false } = option - return new Promise((resolve, reject) => { - if (!force && document.querySelector(`img[src="${src}"]`)) { - resolve(true) - return - } - const dom: HTMLImageElementEX = document.createElement('img') - let attr: keyof ImageAttributes, prop: keyof ImageAttributes - if (attrs) { - for (attr in attrs) { - dom[attr] = attrs[attr] as never - } - } - if (props) { - for (prop in props) { - dom[prop] = props[prop] as never - } - } - dom.src = src - document.body.appendChild(dom) - dom.onload = dom.onreadystatechange = function () { - if (!dom.readyState || ['loaded', 'complete'].includes(dom.readyState)) { - dom.onload = dom.onreadystatechange = null - resolve(true) - } - } - dom.onerror = reject - }) -} - -export default mountImg diff --git a/src/mountJs.ts b/src/mountJs.ts deleted file mode 100644 index 8a73c933..00000000 --- a/src/mountJs.ts +++ /dev/null @@ -1,67 +0,0 @@ -export type ScriptAttributes = Pick< - HTMLScriptElement, - | 'async' - | 'charset' - | 'crossOrigin' - | 'defer' - | 'event' - | 'htmlFor' - | 'integrity' - | 'noModule' - | 'referrerPolicy' - | 'src' - | 'text' - | 'type' -> - -export interface HTMLScriptElementEX extends HTMLScriptElement { - onreadystatechange?: any - readyState?: 'loaded' | 'complete' -} - -export interface JsOptions { - attrs?: ScriptAttributes - props?: ScriptAttributes - force?: boolean -} - -/** - * 动态加载js链接资源 - * - * @param src - 资源地址 - * @param option - 参数: attrs, props, force - * @returns - result - */ -function mountJs(src: string, option: JsOptions): Promise { - if (!src) throw new Error('[mountJs]:url不能为空') - const { attrs, props, force = false } = option - return new Promise((resolve, reject) => { - if (!force && document.querySelector(`script[src="${src}"]`)) { - resolve(true) - return - } - const dom: HTMLScriptElementEX = document.createElement('script') - let attr: keyof ScriptAttributes, prop: keyof ScriptAttributes - if (attrs) { - for (attr in attrs) { - dom[attr] = attrs[attr] as never - } - } - if (props) { - for (prop in props) { - dom[prop] = props[prop] as never - } - } - dom.src = src - document.body.appendChild(dom) - dom.onload = dom.onreadystatechange = function () { - if (!dom.readyState || ['loaded', 'complete'].includes(dom.readyState)) { - dom.onload = dom.onreadystatechange = null - resolve(true) - } - } - dom.onerror = reject - }) -} - -export default mountJs diff --git a/src/mountStyle.ts b/src/mountStyle.ts deleted file mode 100644 index b7cd85df..00000000 --- a/src/mountStyle.ts +++ /dev/null @@ -1,42 +0,0 @@ -export type StyleAttributes = Pick - -export interface StyleOptions { - attrs?: StyleAttributes - props?: StyleAttributes -} - -/** - * 动态加载css样式 - * - * @param src - css string - * @param option - 参数: attrs, props - * @returns - result - */ -function mountStyle(css: string, option: StyleOptions): Promise { - if (!css) throw new Error('[mountStyle]:css不能为空') - const { attrs, props } = option - return new Promise(resolve => { - const dom = document.createElement('style') - let attr: keyof StyleAttributes, prop: keyof StyleAttributes - if (attrs) { - for (attr in attrs) { - dom[attr] = attrs[attr] as never - } - } - if (props) { - for (prop in props) { - dom[prop] = props[prop] as never - } - } - dom.type = 'text/css' - try { - dom.appendChild(document.createTextNode(css)) - } catch (ex) { - dom.textContent = css - } - document.getElementsByTagName('head')[0].appendChild(dom) - resolve(true) - }) -} - -export default mountStyle