# 通用工具模块(TsCommon) **本文档引用的文件** - [TsCommon.js](file://src/utils/TsCommon.js) - [TsStorage.js](file://src/utils/TsStorage.js) - [TsCrypto.js](file://src/utils/TsCrypto.js) - [TsGlobalConfig.js](file://src/utils/TsGlobalConfig.js) - [TsSM4.js](file://src/utils/TsSM4.js) - [TsHttpUtil.js](file://src/https/TsHttpUtil.js) - [index.js](file://index.js) - [package.json](file://package.json) - [README.md](file://README.md) ## 目录 1. [简介](#简介) 2. [项目结构](#项目结构) 3. [核心组件](#核心组件) 4. [架构概览](#架构概览) 5. [详细组件分析](#详细组件分析) 6. [依赖关系分析](#依赖关系分析) 7. [性能考虑](#性能考虑) 8. [故障排除指南](#故障排除指南) 9. [结论](#结论) 10. [附录](#附录) ## 简介 通用工具模块(TsCommon)是一个专为前端开发设计的JavaScript工具库,提供了日常开发中最常用的工具函数集合。该模块采用模块化设计,支持浏览器和Node.js环境,具有以下特点: - **轻量级设计**:专注于核心工具函数,避免功能冗余 - **环境适配**:智能检测运行环境,提供跨平台兼容性 - **错误安全**:完善的异常处理机制,确保函数调用的稳定性 - **易于扩展**:清晰的模块接口,便于功能扩展和维护 该工具模块主要服务于企业级应用开发,特别是在需要统一工具函数管理的大型项目中发挥重要作用。 ## 项目结构 项目采用清晰的模块化组织结构,按照功能域进行文件分类: ```mermaid graph TB subgraph "项目根目录" Root[index.js] Package[package.json] Readme[README.md] end subgraph "源代码目录" Utils[src/utils/] Https[src/https/] end subgraph "工具模块" Common[TsCommon.js] Storage[TsStorage.js] Crypto[TsCrypto.js] SM4[TsSM4.js] GlobalConfig[TsGlobalConfig.js] HttpUtil[TsHttpUtil.js] end subgraph "HTTP模块" HttpUtil end Root --> Utils Root --> Https Utils --> Common Utils --> Storage Utils --> Crypto Utils --> SM4 Utils --> GlobalConfig Https --> HttpUtil ``` **图表来源** - [index.js:1-16](file://index.js#L1-L16) - [package.json:1-24](file://package.json#L1-L24) **章节来源** - [index.js:1-16](file://index.js#L1-L16) - [package.json:1-24](file://package.json#L1-L24) ## 核心组件 TsCommon模块提供了7个核心工具函数,每个函数都针对特定的开发场景进行了优化: ### 主要功能函数 | 函数名称 | 功能描述 | 返回类型 | 使用场景 | |---------|----------|----------|----------| | getParamFormUrl | 从URL中提取指定参数值 | String | URL参数解析、路由参数处理 | | isEmpty | 检查值是否为空 | Boolean | 数据验证、条件判断 | | parseJSON | 安全解析JSON字符串 | Any | 数据序列化、API响应处理 | | split | 分割字符串为数组 | Array | 数据处理、配置解析 | | isDevelopment | 检测开发环境 | Boolean | 环境配置、调试控制 | | replaceAll | 替换所有匹配字符 | String | 文本处理、数据清洗 | | endWith | 检查字符串结尾 | Boolean | 文件类型判断、路径处理 | **章节来源** - [TsCommon.js:1-98](file://src/utils/TsCommon.js#L1-L98) ## 架构概览 TsCommon模块采用简洁的函数式编程模式,所有工具函数都是独立的纯函数,不依赖外部状态。模块间通过明确的依赖关系协作,形成完整的工具生态系统。 ```mermaid graph TD subgraph "TsCommon模块" CommonFunctions[TsCommon.js] UrlParser[URL参数解析] ValueChecker[空值检查] JsonParser[JSON解析] StringProcessor[字符串处理] EnvDetector[环境检测] end subgraph "依赖模块" Storage[TsStorage.js] Crypto[TsCrypto.js] GlobalConfig[TsGlobalConfig.js] SM4[TsSM4.js] end subgraph "上层应用" HttpUtil[TsHttpUtil.js] BusinessLogic[业务逻辑层] end CommonFunctions --> UrlParser CommonFunctions --> ValueChecker CommonFunctions --> JsonParser CommonFunctions --> StringProcessor CommonFunctions --> EnvDetector HttpUtil --> CommonFunctions HttpUtil --> Storage HttpUtil --> Crypto Crypto --> SM4 Storage --> CommonFunctions BusinessLogic --> CommonFunctions ``` **图表来源** - [TsCommon.js:1-98](file://src/utils/TsCommon.js#L1-L98) - [TsHttpUtil.js:1-171](file://src/https/TsHttpUtil.js#L1-L171) - [TsStorage.js:1-55](file://src/utils/TsStorage.js#L1-L55) - [TsCrypto.js:1-34](file://src/utils/TsCrypto.js#L1-L34) - [TsSM4.js:1-456](file://src/utils/TsSM4.js#L1-L456) ## 详细组件分析 ### URL参数解析函数 #### getParamFormUrl函数 该函数专门用于从URL中提取指定的查询参数值,支持自定义主机地址和参数键名。 ```mermaid sequenceDiagram participant Client as 客户端 participant Common as TsCommon participant Browser as 浏览器环境 participant Regex as 正则表达式 Client->>Common : getParamFormUrl(key, host?) Common->>Browser : 获取当前页面URL Browser-->>Common : 返回完整URL Common->>Regex : 创建参数匹配正则 Regex-->>Common : 返回匹配结果 Common->>Common : 解码URI编码值 Common-->>Client : 返回参数值或空字符串 Note over Common : 异常处理:解析失败返回空字符串 ``` **图表来源** - [TsCommon.js:4-18](file://src/utils/TsCommon.js#L4-L18) **函数签名**: `getParamFormUrl(key: string, host?: string): string` **参数说明**: - `key`: 必需,要提取的参数键名 - `host`: 可选,自定义URL地址,默认使用当前页面URL **返回值**: 提取到的参数值,如果未找到则返回空字符串 **使用示例**: ```javascript // 从当前页面URL提取参数 const userId = Common.getParamFormUrl('userId'); // 从指定URL提取参数 const token = Common.getParamFormUrl('token', 'https://api.example.com?token=abc123'); ``` **章节来源** - [TsCommon.js:4-18](file://src/utils/TsCommon.js#L4-L18) ### 空值检查函数 #### isEmpty函数 提供统一的空值检查机制,覆盖JavaScript中常见的空值情况。 **函数签名**: `isEmpty(value: any): boolean` **功能特性**: - 检测 `undefined` 值 - 检测 `null` 值 - 检测空字符串 `''` - 支持任意数据类型的空值判断 **使用场景**: - 表单数据验证 - API响应数据处理 - 条件渲染控制 **章节来源** - [TsCommon.js:25-27](file://src/utils/TsCommon.js#L25-L27) ### JSON解析函数 #### parseJSON函数 提供安全的JSON解析功能,包含异常处理和默认值机制。 ```mermaid flowchart TD Start([函数调用]) --> ParseJSON["尝试解析JSON字符串"] ParseJSON --> ParseSuccess{"解析成功?"} ParseSuccess --> |是| ValidateResult["验证解析结果"] ParseSuccess --> |否| UseDefault["使用默认值"] ValidateResult --> ResultValid{"结果有效?"} ResultValid --> |是| ReturnResult["返回解析结果"] ResultValid --> |否| UseDefault UseDefault --> ReturnDefault["返回默认值"] ReturnResult --> End([结束]) ReturnDefault --> End ``` **图表来源** - [TsCommon.js:34-44](file://src/utils/TsCommon.js#L34-L44) **函数签名**: `parseJSON(value: string, def?: any): any` **参数说明**: - `value`: 必需,要解析的JSON字符串 - `def`: 可选,默认返回值,默认为 `{}` **返回值**: 解析后的对象或提供的默认值 **使用示例**: ```javascript // 基本使用 const userData = Common.parseJSON('{"name":"John"}'); // 自定义默认值 const config = Common.parseJSON('invalid-json', {theme:'dark'}); ``` **章节来源** - [TsCommon.js:34-44](file://src/utils/TsCommon.js#L34-L44) ### 字符串分割函数 #### split函数 提供灵活的字符串分割功能,支持自定义分隔符。 **函数签名**: `split(obj: string, seq?: string): string[]` **参数说明**: - `obj`: 必需,要分割的字符串 - `seq`: 可选,分隔符,默认为逗号 `,` **返回值**: 分割后的字符串数组 **使用示例**: ```javascript // 默认逗号分隔 const tags = Common.split('javascript,python,java'); // 自定义分隔符 const items = Common.split('apple|banana|orange', '|'); ``` **章节来源** - [TsCommon.js:51-56](file://src/utils/TsCommon.js#L51-L56) ### 开发环境检测函数 #### isDevelopment函数 提供统一的环境检测机制,支持多种环境配置方式。 **函数签名**: `isDevelopment(): boolean` **功能特性**: - 检测 `process.env.NODE_ENV` 环境变量 - 支持开发环境标识 - 返回布尔值结果 **使用场景**: - 条件调试输出 - 开发/生产环境配置切换 - API地址环境区分 **章节来源** - [TsCommon.js:63-65](file://src/utils/TsCommon.js#L63-L65) ### 字符串替换函数 #### replaceAll函数 提供全局字符串替换功能,支持正则表达式模式。 **函数签名**: `replaceAll(string: string, s1: string, s2: string): string` **参数说明**: - `string`: 必需,原字符串 - `s1`: 必需,要被替换的子字符串 - `s2`: 必需,替换后的字符串 **返回值**: 替换后的字符串 **使用示例**: ```javascript // 替换所有特殊字符 const cleanText = Common.replaceAll('hello world!', ' ', ''); // HTML标签清理 const plainText = Common.replaceAll('

Hello

', '<[^>]*>', ''); ``` **章节来源** - [TsCommon.js:74-76](file://src/utils/TsCommon.js#L74-L76) ### 字符串结尾检查函数 #### endWith函数 提供字符串结尾检查功能,支持多字符结尾判断。 **函数签名**: `endWith(string?: string, endStr?: string): boolean` **参数说明**: - `string`: 可选,要检查的字符串,默认为空字符串 - `endStr`: 必需,要检查的结尾字符串 **返回值**: 如果字符串以指定后缀结尾返回true,否则false **使用示例**: ```javascript // 检查文件扩展名 const isImage = Common.endWith('photo.jpg', '.jpg'); // 检查URL结尾 const isApiEndpoint = Common.endWith('/api/users', '/users'); ``` **章节来源** - [TsCommon.js:84-87](file://src/utils/TsCommon.js#L84-L87) ## 依赖关系分析 TsCommon模块与其他模块之间存在清晰的依赖关系,形成了完整的工具生态系统。 ```mermaid graph LR subgraph "TsCommon核心" Common[TsCommon.js] end subgraph "直接依赖" Storage[TsStorage.js] Crypto[TsCrypto.js] GlobalConfig[TsGlobalConfig.js] end subgraph "间接依赖" SM4[TsSM4.js] Base64[base64-js] UmiRequest[umi-request] end subgraph "外部依赖" BrowserEnv[浏览器环境] NodeEnv[Node.js环境] end Common --> Storage Common --> GlobalConfig Storage --> Common Crypto --> SM4 Crypto --> Base64 Crypto --> GlobalConfig SM4 --> Base64 HttpUtil --> Common HttpUtil --> Storage HttpUtil --> Crypto HttpUtil --> GlobalConfig HttpUtil --> UmiRequest Common -.-> BrowserEnv Common -.-> NodeEnv Storage -.-> BrowserEnv Crypto -.-> NodeEnv ``` **图表来源** - [TsCommon.js:1-98](file://src/utils/TsCommon.js#L1-L98) - [TsStorage.js:1-55](file://src/utils/TsStorage.js#L1-L55) - [TsCrypto.js:1-34](file://src/utils/TsCrypto.js#L1-L34) - [TsSM4.js:1-456](file://src/utils/TsSM4.js#L1-L456) - [TsHttpUtil.js:1-171](file://src/https/TsHttpUtil.js#L1-L171) - [package.json:19-22](file://package.json#L19-L22) ### 模块间交互流程 ```mermaid sequenceDiagram participant App as 应用程序 participant HttpUtil as HTTP工具 participant Storage as 存储工具 participant Crypto as 加密工具 participant Common as 通用工具 App->>HttpUtil : 发起HTTP请求 HttpUtil->>Common : 使用isEmpty检查数据 HttpUtil->>Storage : 获取用户令牌 Storage->>Common : 使用parseJSON解析数据 HttpUtil->>Crypto : 加密请求数据 Crypto->>Crypto : 使用SM4算法 Crypto-->>HttpUtil : 返回加密结果 HttpUtil-->>App : 返回处理后的响应 ``` **图表来源** - [TsHttpUtil.js:99-134](file://src/https/TsHttpUtil.js#L99-L134) - [TsStorage.js:41-43](file://src/utils/TsStorage.js#L41-L43) - [TsCrypto.js:19-30](file://src/utils/TsCrypto.js#L19-L30) **章节来源** - [TsCommon.js:1-98](file://src/utils/TsCommon.js#L1-L98) - [TsStorage.js:1-55](file://src/utils/TsStorage.js#L1-L55) - [TsCrypto.js:1-34](file://src/utils/TsCrypto.js#L1-L34) - [TsSM4.js:1-456](file://src/utils/TsSM4.js#L1-L456) - [TsHttpUtil.js:1-171](file://src/https/TsHttpUtil.js#L1-L171) ## 性能考虑 ### 时间复杂度分析 | 函数 | 时间复杂度 | 空间复杂度 | 说明 | |------|------------|------------|------| | getParamFormUrl | O(n) | O(1) | n为URL长度,正则匹配 | | isEmpty | O(1) | O(1) | 常数时间比较 | | parseJSON | O(n) | O(n) | n为字符串长度,JSON解析 | | split | O(n) | O(n) | n为字符串长度,字符串分割 | | isDevelopment | O(1) | O(1) | 环境变量读取 | | replaceAll | O(n*m) | O(n+m) | n为原字符串长度,m为匹配次数 | | endWith | O(m) | O(1) | m为endStr长度 | ### 内存使用优化 1. **字符串处理优化**: 所有字符串操作都使用原生JavaScript方法,避免额外的内存分配 2. **正则表达式复用**: URL参数解析中的正则表达式在函数内部创建,避免重复编译 3. **异常处理**: 所有函数都有完善的异常处理,防止内存泄漏 ### 缓存策略 - URL参数解析结果不进行缓存,因为每次调用可能使用不同的URL - 环境检测结果可缓存,但当前实现每次都重新检查以确保准确性 ## 故障排除指南 ### 常见问题及解决方案 #### URL参数解析失败 **问题**: `getParamFormUrl` 返回空字符串 **原因**: - URL中不存在指定参数 - URL格式不正确 - 浏览器环境限制 **解决方案**: ```javascript // 检查URL格式 const url = Common.getParamFormUrl('key', customUrl); if (!url) { console.warn('参数解析失败,检查URL格式'); } // 使用默认值 const value = Common.getParamFormUrl('key') || defaultValue; ``` #### JSON解析异常 **问题**: `parseJSON` 抛出异常或返回错误结果 **原因**: - 输入不是有效的JSON格式 - 字符串包含特殊字符 **解决方案**: ```javascript // 使用try-catch处理 let result; try { result = Common.parseJSON(jsonString); } catch (error) { console.error('JSON解析失败:', error); result = defaultValue; } // 或者使用默认值机制 const data = Common.parseJSON(invalidJson, {}); ``` #### 环境检测不准确 **问题**: `isDevelopment` 返回错误的环境信息 **原因**: - `NODE_ENV` 环境变量未正确设置 - 在浏览器环境中无法访问Node.js环境变量 **解决方案**: ```javascript // 检查环境变量 console.log('NODE_ENV:', process.env.NODE_ENV); // 在浏览器环境中使用其他方式检测 const isDev = typeof window !== 'undefined' && window.location.hostname === 'localhost'; ``` ### 调试技巧 1. **启用详细日志**: 在开发环境中使用 `isDevelopment` 函数控制日志输出 2. **参数验证**: 在调用工具函数前验证输入参数的有效性 3. **异常捕获**: 对可能失败的函数调用使用try-catch包装 **章节来源** - [TsCommon.js:7-17](file://src/utils/TsCommon.js#L7-L17) - [TsCommon.js:36-42](file://src/utils/TsCommon.js#L36-L42) ## 结论 TsCommon通用工具模块通过提供7个核心工具函数,为JavaScript开发提供了坚实的基础工具集。该模块具有以下优势: 1. **功能完备**: 覆盖了日常开发中最常用的工具函数 2. **设计优雅**: 采用纯函数设计,无副作用,易于测试 3. **环境友好**: 支持浏览器和Node.js双环境运行 4. **错误安全**: 完善的异常处理机制,确保程序稳定性 5. **易于扩展**: 清晰的模块接口,便于功能扩展 该模块特别适用于需要统一工具函数管理的企业级应用开发,能够显著提高开发效率和代码质量。通过合理的依赖管理和模块化设计,TsCommon为整个工具库生态系统奠定了坚实的基础。 ## 附录 ### API参考表 #### URL处理函数 | 函数名 | 参数 | 返回值 | 描述 | |--------|------|--------|------| | getParamFormUrl | `(key: string, host?: string)` | `string` | 从URL中提取参数值 | | endWith | `(string?: string, endStr?: string)` | `boolean` | 检查字符串是否以指定后缀结尾 | #### 数据处理函数 | 函数名 | 参数 | 返回值 | 描述 | |--------|------|--------|------| | isEmpty | `(value: any)` | `boolean` | 检查值是否为空 | | parseJSON | `(value: string, def?: any)` | `any` | 安全解析JSON字符串 | | split | `(obj: string, seq?: string)` | `string[]` | 分割字符串为数组 | #### 字符串处理函数 | 函数名 | 参数 | 返回值 | 描述 | |--------|------|--------|------| | replaceAll | `(string: string, s1: string, s2: string)` | `string` | 替换所有匹配的子字符串 | #### 环境检测函数 | 函数名 | 参数 | 返回值 | 描述 | |--------|------|--------|------| | isDevelopment | `()` | `boolean` | 检测是否为开发环境 | ### 最佳实践建议 1. **参数验证**: 在调用任何工具函数前,先使用 `isEmpty` 验证输入参数 2. **错误处理**: 对可能失败的函数调用使用适当的异常处理机制 3. **环境适配**: 使用 `isDevelopment` 控制开发和生产环境的不同行为 4. **性能优化**: 对于频繁调用的函数,考虑缓存结果以提高性能 5. **代码复用**: 将常用的工具函数组合成更高层的业务函数 ### 版本兼容性 - **Node.js版本**: 支持Node.js 12及以上版本 - **浏览器兼容**: 支持现代浏览器(Chrome 60+, Firefox 55+, Safari 11+) - **ES版本**: 使用ES6+语法,需要相应的转译配置