youtil 2.0.3 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cjs/index.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ export * from './loading';
2
+ export * from './param';
3
+ export * from './request';
4
+ export * from './time';
5
+ /**
6
+ * 基于JSON的简单深拷贝
7
+ * @param obj 要复制的对象,非对象格式会直接返回
8
+ * @returns
9
+ */
10
+ export declare const deepCopy: (obj: any) => any;
11
+ /**
12
+ * HTML编码,例如将 【"】 变成 【"】
13
+ * @param {*} html 待编码的原始字符串,如果传入对象会遍历处理
14
+ * @returns
15
+ */
16
+ export declare const encodeHtml: (html: string | any) => any;
17
+ /**
18
+ * HTML解码,例如将 【"】 变成 【"】
19
+ * @param {*} html 已经被HTML编码过的字符串,如果传入对象会遍历处理
20
+ * @returns
21
+ */
22
+ export declare const decodeHtml: (html: string | any) => any;
23
+ /**
24
+ * 复制一段文本到剪贴板,如果失败会抛出异常,推荐使用姿势:
25
+ * await copyTextToClipboard('要复制的文本', message => alert(`复制到剪贴板失败:${message}`));
26
+ * alert('复制到剪贴板成功!');
27
+ * @param {*} text 要复制的文本
28
+ * @param {*} onFailure 失败回调,接受一个 message 参数
29
+ * @param {*} supportSilent 是否支持后台静默复制,如果是则优先采用 execCommand
30
+ * @returns
31
+ */
32
+ export declare const copyToClipboard: (text: string, onFailure: (message: string) => void, supportSilent: boolean) => Promise<void>;
package/cjs/index.js ADDED
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ deepCopy: function() {
13
+ return deepCopy;
14
+ },
15
+ encodeHtml: function() {
16
+ return encodeHtml;
17
+ },
18
+ decodeHtml: function() {
19
+ return decodeHtml;
20
+ },
21
+ copyToClipboard: function() {
22
+ return copyToClipboard;
23
+ }
24
+ });
25
+ var _exportStar = require("@swc/helpers/lib/_export_star.js").default;
26
+ _exportStar(require("./loading"), exports);
27
+ _exportStar(require("./param"), exports);
28
+ _exportStar(require("./request"), exports);
29
+ _exportStar(require("./time"), exports);
30
+ var deepCopy = function(obj) {
31
+ if (!obj || typeof obj !== "object") return obj;
32
+ return JSON.parse(JSON.stringify(obj));
33
+ };
34
+ var encodeHtml = function(html) {
35
+ if (typeof html === "string") {
36
+ var div = document.createElement("div");
37
+ div.innerText = html;
38
+ return div.innerHTML;
39
+ } else if (typeof html === "object" && html) for(var i in html)html[i] = encodeHtml(html[i]);
40
+ return html;
41
+ };
42
+ var decodeHtml = function(html) {
43
+ if (typeof html === "string") {
44
+ var div = document.createElement("div");
45
+ div.innerHTML = html;
46
+ return div.innerText;
47
+ } else if (typeof html === "object" && html) for(var i in html)html[i] = decodeHtml(html[i]);
48
+ return html;
49
+ };
50
+ var copyToClipboard = function(text, onFailure, supportSilent) {
51
+ if (!text) throw new Error("text can not be empty.");
52
+ onFailure = onFailure || function(msg) {
53
+ return console.error("复制到剪贴板失败:".concat(msg || ""));
54
+ };
55
+ // 优先采用现代化API
56
+ if (navigator.clipboard && !supportSilent) // 注意 writeText API 要求:文档被激活 & 页面已启用HTTPS
57
+ return navigator.clipboard.writeText(text).catch(function(e) {
58
+ onFailure(e.message);
59
+ throw e;
60
+ });
61
+ // execCommand 原本是一个同步API,这里为了和 writeText 保持一致统一包成proimse
62
+ return new Promise(function(resolve, reject) {
63
+ var input = document.createElement("input");
64
+ input.value = text;
65
+ input.style.cssText = "position:fixed;left:0;top:0;opacity:0;";
66
+ document.body.appendChild(input);
67
+ input.select();
68
+ try {
69
+ if (document.execCommand("copy")) resolve();
70
+ else {
71
+ var message = "Failed to execute 'document.execCommand'.";
72
+ onFailure(message);
73
+ reject(new Error(message));
74
+ }
75
+ } catch (e) {
76
+ onFailure(e.message);
77
+ reject(e);
78
+ } finally{
79
+ document.body.removeChild(input);
80
+ }
81
+ });
82
+ };
@@ -0,0 +1,19 @@
1
+ /** showLoading配置 */
2
+ export interface IShowLoadingConfig {
3
+ hasMask?: boolean;
4
+ maskColor?: string;
5
+ cancelInline?: boolean;
6
+ onCancel?: Function;
7
+ id?: string;
8
+ }
9
+ /**
10
+ * 显示全局loading,不依赖任何框架
11
+ * @param {*} text 提示文案
12
+ * @param {*} seconds 超时自动关闭时间,单位秒
13
+ * @param {*} options 可选配置
14
+ */
15
+ export declare const showLoading: (text?: string, seconds?: number, config?: IShowLoadingConfig) => void;
16
+ /**
17
+ * 主动关闭loading提示
18
+ */
19
+ export declare const hideLoading: () => void;
package/cjs/loading.js ADDED
@@ -0,0 +1,63 @@
1
+ /** showLoading配置 */ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ showLoading: function() {
13
+ return showLoading;
14
+ },
15
+ hideLoading: function() {
16
+ return hideLoading;
17
+ }
18
+ });
19
+ var showLoading = function() {
20
+ var text = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "请稍候", seconds = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 10, config = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
21
+ var defaultConfig = {
22
+ hasMask: true,
23
+ maskColor: "transparent",
24
+ onCancel: null,
25
+ cancelInline: false,
26
+ id: "com_global_page_loading"
27
+ };
28
+ config = Object.assign({}, defaultConfig, config);
29
+ var id = config.id;
30
+ var timeoutKey = "_".concat(id, "_timeout");
31
+ if (window[timeoutKey]) clearTimeout(window[timeoutKey]);
32
+ var dom = document.getElementById(id);
33
+ if (!dom) {
34
+ dom = document.createElement("div");
35
+ dom.id = id;
36
+ dom.className = id;
37
+ document.body.append(dom);
38
+ }
39
+ var styleId = "".concat(id, "_style");
40
+ if (!document.getElementById(styleId)) {
41
+ var style = document.createElement("style");
42
+ style.id = styleId;
43
+ style.innerHTML = "\n .".concat(id, " {\n position: fixed;\n top: calc(50vh - 60px);\n left: calc(50vw - 60px);\n width: 120px;\n height: 120px;\n z-index: 8000;\n background: rgba(0, 0, 0, 0.6);\n border-radius: 8px;\n text-align: center;\n color: white;\n padding-top: 20px;\n }\n .").concat(id, " img {\n width: 50px;\n margin-bottom: 10px;\n }");
44
+ document.head.appendChild(style);
45
+ }
46
+ dom.innerHTML = "\n ".concat(config.hasMask ? '<div class="mask-wrapper" style="background-color: '.concat(config.maskColor, '"></div>') : "", '\n <div class="loading-wrapper">\n <div class="loading-content">\n <img src="https://img.alicdn.com/tfs/TB1bnUsQBLoK1RjSZFuXXXn0XXa-32-32.svg" alt="加载中">\n <div>').concat(text).concat(config.cancelInline ? " " : "</div>", "\n ").concat(config.onCancel ? '<a href="javascript:;" class="cancel">取消</a>' : "", "\n ").concat(config.cancelInline ? "</div>" : "", "\n </div>\n </div>");
47
+ if (config.onCancel) {
48
+ var btn = dom.querySelector(".cancel");
49
+ btn && btn.addEventListener("click", function() {
50
+ hideLoading();
51
+ config.onCancel();
52
+ });
53
+ }
54
+ dom.style.display = "block";
55
+ if (seconds > 0) window[timeoutKey] = setTimeout(function() {
56
+ hideLoading();
57
+ }, seconds * 1000);
58
+ };
59
+ var hideLoading = function() {
60
+ var id = "com_global_page_loading";
61
+ var loading = document.getElementById(id);
62
+ if (loading) loading.style.display = "none";
63
+ };
package/cjs/param.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * 从URL中获取某个参数,如果不存在返回 undefined ,如果存在多个同名参数,返回第一个匹配值
3
+ * getParam('a', '?a=1&b=&c=3&c=33#abc') // '1'
4
+ * getParam('b', '?a=1&b=&c=3&c=33#abc') // ''
5
+ * getParam('c', '?a=1&b=&c=3&c=33#abc') // 3
6
+ * getParam('d', '?a=1&b=&c=3&c=33#abc') // undefined
7
+ * @param {*} name 参数名
8
+ * @param {*} url 要获取的URL,默认当前地址
9
+ */
10
+ export declare const getParam: (name: string, url?: string) => string;
11
+ /**
12
+ * 从URL中获取int参数
13
+ * @param {*} name 参数名
14
+ * @param {*} url 要获取的URL,默认当前地址
15
+ */
16
+ export declare const getParamInt: (name: string, url?: string) => number;
17
+ /**
18
+ * 获取某个URL的全部参数
19
+ * getParams('?a=1&b=2#cc') // {a: '1', b: '2'}
20
+ * @param url
21
+ * @returns 参数对象
22
+ */
23
+ export declare const getParams: (url?: string) => any;
24
+ /**
25
+ * 给URL设置参数,如果已经存在,替换之,兼容hash存在的情况
26
+ * setParam('a', '123', '?a=1&b=2&a=3#d') // '?a=123&b=2&a=123#d'
27
+ * setParam('d', '444', '?a=1&b=2&a=3#d') // '?a=1&b=2&a=3&d=444#d'
28
+ * @param {Object} name 参数名
29
+ * @param {Object} value 参数值
30
+ * @param {Object} url 如果不传默认当前页面URL
31
+ */
32
+ export declare const setParam: (name: string, value: string | number, url?: string) => string;
33
+ /**
34
+ * 删除URL中某个参数
35
+ * delParam('a', '?a=1&b=2&a=3#d') // '?b=2#d'
36
+ * delParam('b', '?a=1&b=2&a=3#d') // '?a=1&a=3#d'
37
+ * delParam('a', '?a=1#d') // '#d'
38
+ * @param name 参数名
39
+ * @param url 要删除的URL,默认当前页面URL
40
+ * @returns 处理完后的URL
41
+ */
42
+ export declare const delParam: (name: string, url: string) => string;
43
+ /**
44
+ * 将一个普通对象转为 a=1&b=2 的URL格式,会自动过滤undefined的值
45
+ * @param data 一个普通对象,如果对象嵌对象则会被自动转为JSON
46
+ * @returns 返回类似 a=1&b=2 的字符串
47
+ */
48
+ export declare const toUrlParams: (data: any) => string;
package/cjs/param.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * 从URL中获取某个参数,如果不存在返回 undefined ,如果存在多个同名参数,返回第一个匹配值
3
+ * getParam('a', '?a=1&b=&c=3&c=33#abc') // '1'
4
+ * getParam('b', '?a=1&b=&c=3&c=33#abc') // ''
5
+ * getParam('c', '?a=1&b=&c=3&c=33#abc') // 3
6
+ * getParam('d', '?a=1&b=&c=3&c=33#abc') // undefined
7
+ * @param {*} name 参数名
8
+ * @param {*} url 要获取的URL,默认当前地址
9
+ */ "use strict";
10
+ Object.defineProperty(exports, "__esModule", {
11
+ value: true
12
+ });
13
+ function _export(target, all) {
14
+ for(var name in all)Object.defineProperty(target, name, {
15
+ enumerable: true,
16
+ get: all[name]
17
+ });
18
+ }
19
+ _export(exports, {
20
+ getParam: function() {
21
+ return getParam;
22
+ },
23
+ getParamInt: function() {
24
+ return getParamInt;
25
+ },
26
+ getParams: function() {
27
+ return getParams;
28
+ },
29
+ setParam: function() {
30
+ return setParam;
31
+ },
32
+ delParam: function() {
33
+ return delParam;
34
+ },
35
+ toUrlParams: function() {
36
+ return toUrlParams;
37
+ }
38
+ });
39
+ var _slicedToArray = require("@swc/helpers/lib/_sliced_to_array.js").default;
40
+ var getParam = function(name) {
41
+ var url = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : location.search;
42
+ return (new RegExp("(^|\\?|&)".concat(name, "=(.*?)(?=&|#|$)"), "g").exec(url) || [])[2];
43
+ };
44
+ var getParamInt = function(name) {
45
+ var url = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : location.search;
46
+ return parseInt(getParam(name, url) || "0", 10);
47
+ };
48
+ var getParams = function() {
49
+ var url = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : location.search;
50
+ var search = ((url || "").split("?").pop() || "").split("#")[0] || "";
51
+ var params = {};
52
+ search.split("&").map(function(item) {
53
+ return item.split("=");
54
+ }).forEach(function(param) {
55
+ var _param = _slicedToArray(param, 2), key = _param[0], value = _param[1];
56
+ params[key] = value || "";
57
+ });
58
+ return params;
59
+ };
60
+ var setParam = function(name, value, url) {
61
+ url = url || "".concat(location.pathname).concat(location.search);
62
+ // 如果参数已经存在,替换之
63
+ if (getParam(name, url) !== undefined) return url.replace(new RegExp("(^|\\?|&)".concat(name, "=(.*?)(?=&|#|$)"), "g"), "$1".concat(name, "=").concat(value));
64
+ var _url_split = _slicedToArray(url.split("#"), 2), pathname = _url_split[0], hash = _url_split[1]; // 处理存在hash的情况
65
+ return "".concat(pathname).concat(pathname.indexOf("?") < 0 ? "?" : "&").concat(name, "=").concat(value).concat(hash ? "#" : "").concat(hash || "");
66
+ };
67
+ var delParam = function(name, url) {
68
+ url = url || "".concat(location.pathname).concat(location.search);
69
+ return url.replace(new RegExp("(^|\\?|&)".concat(name, "=.*?(&|#|$)"), "g"), function(_m, $1, $2) {
70
+ return $2 === "&" ? $1 : $2;
71
+ });
72
+ };
73
+ var toUrlParams = function(data) {
74
+ return Object.keys(data || {}).filter(function(key) {
75
+ return data[key] !== undefined;
76
+ }).map(function(key) {
77
+ var value = typeof data[key] === "object" ? JSON.stringify(data[key]) : data[key];
78
+ return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(value));
79
+ }).join("&");
80
+ };
@@ -0,0 +1,48 @@
1
+ /** requestAPI的第二个参数类型 */
2
+ export interface IRequestOptions {
3
+ /** GET请求时传递的参数 */
4
+ params?: Record<string, any>;
5
+ /** POST请求时传递的参数 */
6
+ data?: Record<string, any>;
7
+ /** postJson请求时传递的参数 */
8
+ json?: Record<string, any>;
9
+ /** API前缀,不传默认为空 */
10
+ baseUrl?: string;
11
+ /** 请求方法,一般情况下会自动处理无需手动传 */
12
+ method?: string;
13
+ /** headers */
14
+ headers?: Record<string, any>;
15
+ /** 其它自定义fetchOptions */
16
+ fetchOptions?: RequestInit;
17
+ /** 请求完成之后触发的钩子,无论成功与否均会触发 */
18
+ afterRequest?: (success: boolean, resp?: any) => void;
19
+ /** 对响应进行自定义格式化处理 */
20
+ responseConverter?: (resp: any) => any;
21
+ /** 后端未返回 message 时的默认异常文案 */
22
+ errorMessage?: string;
23
+ /** 发生异常时的处理方法,一般不太建议重写此方法 */
24
+ errorHandler?: (message: string, resp?: any) => void;
25
+ /** 自定义toast实现,为了和UI解耦,方法默认不包含UI处理代码 */
26
+ toastHandler?: (message: string) => void;
27
+ /** 判断接口是否调用成功,默认规则 resp => resp.code == 0 || resp.code == 200 */
28
+ checkSuccess?: (resp: any) => boolean;
29
+ /** 是否关闭默认的异常toast */
30
+ silent?: boolean;
31
+ }
32
+ /**
33
+ * 通用的API请求方法
34
+ * @param url
35
+ * @param options
36
+ * @returns
37
+ */
38
+ export declare const request: <T = any>(url: string, options?: IRequestOptions) => Promise<T>;
39
+ type IRequest = typeof request;
40
+ interface RequestConstructor {
41
+ new (overrideOptions: IRequestOptions): IRequest;
42
+ new (req: IRequest, overrideOptions: IRequestOptions): IRequest;
43
+ }
44
+ /**
45
+ * 支持实例化一个新的request方法,覆盖默认的部分配置项
46
+ */
47
+ export declare const Request: RequestConstructor;
48
+ export {};
package/cjs/request.js ADDED
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ request: function() {
13
+ return request;
14
+ },
15
+ Request: function() {
16
+ return Request;
17
+ }
18
+ });
19
+ var _asyncToGenerator = require("@swc/helpers/lib/_async_to_generator.js").default;
20
+ var _objectSpread = require("@swc/helpers/lib/_object_spread.js").default;
21
+ var _tsGenerator = require("@swc/helpers/lib/_ts_generator.js").default;
22
+ var _param = require("./param");
23
+ var request = function() {
24
+ var _ref = _asyncToGenerator(function(url, options) {
25
+ var defaultOptions, _ref, params, data, json, method, headers, baseUrl, fetchOptions, checkSuccess, afterRequest, errorHandler, errorMessage, responseConverter, resp, e;
26
+ return _tsGenerator(this, function(_state) {
27
+ switch(_state.label){
28
+ case 0:
29
+ defaultOptions = {
30
+ errorMessage: "系统繁忙,请稍后再试",
31
+ errorHandler: function(msg) {
32
+ var _options_toastHandler;
33
+ if (!(options === null || options === void 0 ? void 0 : options.silent)) options === null || options === void 0 ? void 0 : (_options_toastHandler = options.toastHandler) === null || _options_toastHandler === void 0 ? void 0 : _options_toastHandler.call(options, msg);
34
+ // 抛出异常,阻止执行之后的操作
35
+ throw new Error(msg);
36
+ },
37
+ baseUrl: "",
38
+ headers: {},
39
+ fetchOptions: {
40
+ credentials: "include"
41
+ },
42
+ // eslint-disable-next-line eqeqeq
43
+ checkSuccess: function(resp) {
44
+ return (resp === null || resp === void 0 ? void 0 : resp.code) == 0 || (resp === null || resp === void 0 ? void 0 : resp.code) == 200;
45
+ },
46
+ toastHandler: function(msg) {
47
+ return console.error("[您还没有配置toastHandler,请根据您的UI组件库配置合适的提示方法] ".concat(msg || ""));
48
+ }
49
+ };
50
+ options = Object.assign({}, defaultOptions, options || {});
51
+ _ref = options || {}, params = _ref.params, data = _ref.data, json = _ref.json, method = _ref.method, headers = _ref.headers, baseUrl = _ref.baseUrl, fetchOptions = _ref.fetchOptions, checkSuccess = _ref.checkSuccess, afterRequest = _ref.afterRequest, errorHandler = _ref.errorHandler, errorMessage = _ref.errorMessage, responseConverter = _ref.responseConverter;
52
+ if (params) {
53
+ fetchOptions.method = method || "GET";
54
+ url = "".concat(url, "?").concat((0, _param.toUrlParams)(params));
55
+ }
56
+ if (data) Object.assign(fetchOptions, {
57
+ method: method || "POST",
58
+ body: (0, _param.toUrlParams)(data),
59
+ headers: _objectSpread({
60
+ "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
61
+ }, headers || {})
62
+ });
63
+ else if (json) Object.assign(fetchOptions, {
64
+ method: method || "POST",
65
+ body: JSON.stringify(json),
66
+ headers: _objectSpread({
67
+ "Content-Type": "application/json;charset=utf-8"
68
+ }, headers || {})
69
+ });
70
+ resp = null;
71
+ _state.label = 1;
72
+ case 1:
73
+ _state.trys.push([
74
+ 1,
75
+ 3,
76
+ ,
77
+ 4
78
+ ]);
79
+ return [
80
+ 4,
81
+ fetch("".concat(baseUrl || "").concat(url), fetchOptions).then(function(res) {
82
+ return res.json();
83
+ })
84
+ ];
85
+ case 2:
86
+ resp = _state.sent();
87
+ return [
88
+ 3,
89
+ 4
90
+ ];
91
+ case 3:
92
+ e = _state.sent();
93
+ console.error(e);
94
+ afterRequest === null || afterRequest === void 0 ? void 0 : afterRequest(false, {
95
+ message: e === null || e === void 0 ? void 0 : e.message
96
+ });
97
+ errorHandler === null || errorHandler === void 0 ? void 0 : errorHandler(errorMessage || "");
98
+ return [
99
+ 2,
100
+ undefined
101
+ ];
102
+ case 4:
103
+ resp = responseConverter ? responseConverter(resp) : resp;
104
+ if (checkSuccess === null || checkSuccess === void 0 ? void 0 : checkSuccess(resp)) {
105
+ afterRequest === null || afterRequest === void 0 ? void 0 : afterRequest(true, resp);
106
+ return [
107
+ 2,
108
+ resp.data
109
+ ];
110
+ } else {
111
+ afterRequest === null || afterRequest === void 0 ? void 0 : afterRequest(false, resp);
112
+ errorHandler === null || errorHandler === void 0 ? void 0 : errorHandler(resp.message || resp.msg || errorMessage || "", resp);
113
+ return [
114
+ 2,
115
+ undefined
116
+ ];
117
+ }
118
+ return [
119
+ 2
120
+ ];
121
+ }
122
+ });
123
+ });
124
+ return function request(url, options) {
125
+ return _ref.apply(this, arguments);
126
+ };
127
+ }();
128
+ var Request = function Request(req, overrideOptions) {
129
+ var overrideDefaultOptions = overrideOptions;
130
+ if (!overrideOptions) {
131
+ overrideDefaultOptions = req;
132
+ req = request;
133
+ }
134
+ return function(url, options) {
135
+ return req(url, _objectSpread({}, overrideDefaultOptions || {}, options || {}));
136
+ };
137
+ };
package/cjs/time.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * 将日期格式化成指定格式的字符串
3
+ * @param date 要格式化的日期,不传时默认当前时间,也可以是一个时间戳等
4
+ * @param fmt 目标字符串格式,支持的字符有:y,M,d,q,w,H,h,m,S,默认:yyyy-MM-dd HH:mm:ss
5
+ * @returns 返回格式化后的日期字符串
6
+ */
7
+ export declare const formatDate: (date?: Date | number | string, fmt?: string) => string;
8
+ /**
9
+ * 将字符串解析成日期
10
+ * @param str 输入的日期字符串,如'2014-09-13'
11
+ * @param fmt 字符串格式,默认'yyyy-MM-dd',支持如下:y、M、d、H、m、s、S,不支持w和q
12
+ * @returns 解析后的Date类型日期
13
+ */
14
+ export declare const parseDate: (str: string, fmt?: string) => Date;
15
+ /**
16
+ * 休息一段时间,单位毫秒
17
+ * 示例:await sleep(200); // 休息200毫秒
18
+ * @param ms 要休息的时间,单位毫秒,不传默认0
19
+ * @returns
20
+ */
21
+ export declare const sleep: (ms?: number) => Promise<unknown>;
package/cjs/time.js ADDED
@@ -0,0 +1,103 @@
1
+ /**
2
+ * 将日期格式化成指定格式的字符串
3
+ * @param date 要格式化的日期,不传时默认当前时间,也可以是一个时间戳等
4
+ * @param fmt 目标字符串格式,支持的字符有:y,M,d,q,w,H,h,m,S,默认:yyyy-MM-dd HH:mm:ss
5
+ * @returns 返回格式化后的日期字符串
6
+ */ "use strict";
7
+ Object.defineProperty(exports, "__esModule", {
8
+ value: true
9
+ });
10
+ function _export(target, all) {
11
+ for(var name in all)Object.defineProperty(target, name, {
12
+ enumerable: true,
13
+ get: all[name]
14
+ });
15
+ }
16
+ _export(exports, {
17
+ formatDate: function() {
18
+ return formatDate;
19
+ },
20
+ parseDate: function() {
21
+ return parseDate;
22
+ },
23
+ sleep: function() {
24
+ return sleep;
25
+ }
26
+ });
27
+ var _instanceof = require("@swc/helpers/lib/_instanceof.js").default;
28
+ var formatDate = function(date, fmt) {
29
+ var _loop = function(i) {
30
+ fmt = fmt.replace(new RegExp("".concat(i, "+"), "g"), function(m) {
31
+ var val = "".concat(obj[i]);
32
+ if (i === "w") return (m.length > 2 ? "星期" : "周") + week[val];
33
+ for(var j = 0, len = val.length; j < m.length - len; j++)val = "0".concat(val);
34
+ return m.length === 1 ? val : val.substring(val.length - m.length);
35
+ });
36
+ };
37
+ if (!date) return "";
38
+ if (typeof date === "number") // 1687682453445
39
+ date = new Date(date);
40
+ else if (typeof date === "string") {
41
+ if (/^\d{12,13}$/g.test(date)) // '1687682453445'
42
+ date = new Date(parseInt(date, 10));
43
+ else if (/^.{10}T.{8,12}Z?$/g.test(date)) // '2019-01-01T00:00:00.000Z'
44
+ date = new Date(date);
45
+ else return date;
46
+ }
47
+ if (!_instanceof(date, Date)) throw new Error("formatDate error: not date.");
48
+ if (isNaN(date === null || date === void 0 ? void 0 : date.getFullYear())) throw new Error("formatDate error: invalid date.");
49
+ fmt = fmt || "yyyy-MM-dd HH:mm:ss";
50
+ var obj = {
51
+ y: date.getFullYear(),
52
+ M: date.getMonth() + 1,
53
+ d: date.getDate(),
54
+ q: Math.floor((date.getMonth() + 3) / 3),
55
+ w: date.getDay(),
56
+ H: date.getHours(),
57
+ h: date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
58
+ m: date.getMinutes(),
59
+ s: date.getSeconds(),
60
+ S: date.getMilliseconds()
61
+ };
62
+ var week = [
63
+ "天",
64
+ "一",
65
+ "二",
66
+ "三",
67
+ "四",
68
+ "五",
69
+ "六"
70
+ ];
71
+ // eslint-disable-next-line guard-for-in
72
+ for(var i in obj)_loop(i);
73
+ return fmt;
74
+ };
75
+ var parseDate = function(str, fmt) {
76
+ fmt = fmt || "yyyy-MM-dd";
77
+ var obj = {
78
+ y: 0,
79
+ M: 1,
80
+ d: 0,
81
+ H: 0,
82
+ h: 0,
83
+ m: 0,
84
+ s: 0,
85
+ S: 0
86
+ };
87
+ fmt.replace(/([^yMdHmsS]*?)(([yMdHmsS])\3*)([^yMdHmsS]*?)/g, function(m, $1, $2, $3, $4) {
88
+ str = str.replace(new RegExp("".concat($1, "(\\d{").concat($2.length, "})").concat($4)), function(_m, _$1) {
89
+ obj[$3] = parseInt(_$1);
90
+ return "";
91
+ });
92
+ return "";
93
+ });
94
+ obj.M--; // 月份是从0开始的,所以要减去1
95
+ var date = new Date(obj.y, obj.M, obj.d, obj.H, obj.m, obj.s);
96
+ if (obj.S !== 0) date.setMilliseconds(obj.S); // 如果设置了毫秒
97
+ return date;
98
+ };
99
+ var sleep = function(ms) {
100
+ return new Promise(function(resolve) {
101
+ return setTimeout(resolve, ms || 0);
102
+ });
103
+ };
package/package.json CHANGED
@@ -1,23 +1,26 @@
1
1
  {
2
2
  "name": "youtil",
3
- "version": "2.0.3",
3
+ "version": "2.0.4",
4
4
  "description": "油梯,一个与框架、环境无关的小巧、精简、实用的JavaScript工具库",
5
5
  "files": [
6
6
  "esm",
7
7
  "cjs",
8
8
  "dist"
9
9
  ],
10
- "main": "esm/index.js",
10
+ "main": "cjs/index.js",
11
11
  "module": "esm/index.js",
12
12
  "types": "esm/index.d.ts",
13
13
  "exports": {
14
14
  ".": {
15
- "default": {
16
- "types": "./esm/index.d.ts",
17
- "default": "./esm/index.js"
18
- }
15
+ "require": "./cjs/index.js",
16
+ "import": "./esm/index.js",
17
+ "types": "./esm/index.d.ts"
19
18
  },
20
- "./*": "./*"
19
+ "./*": {
20
+ "require": "./cjs/*.js",
21
+ "import": "./esm/*.js",
22
+ "types": "./esm/*.d.ts"
23
+ }
21
24
  },
22
25
  "sideEffects": [
23
26
  "dist/*"