关于 cross-platform-compatibility
帮助编写兼容 Windows、macOS 和 Linux 的代码的开发技能。内容涉及路径、平台检测、环境变量、平台差异处理和测试策略,也包括跨平台命令行工具的指导。
主要功能
- 01可移植的文件路径处理
- 02运行时平台检测
- 03换行符与字符编码
- 04环境变量处理
- 05跨平台测试指导
- 06构建与依赖项指导
适用场景
- 01面向多种操作系统开发
- 02处理文件系统操作
- 03构建跨平台命令行工具
- 04管理平台专属依赖项
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ aj-geddes/ useful-ai-prompts --skill cross-platform-compatibility安装后在 Claude Code 中输入/cross-platform-compatibility确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/build-configuration.mdcharacter-encoding.mdenvironment-variables.mdfile-path-handling.mdfile-permissions.mdline-endings.mdplatform-detection.mdplatform-specific-dependencies.mdprocess-management.mdshell-commands.mdtesting-across-platforms.mdscripts/scaffold-tests.shtemplates/test-template.js详细介绍
跨平台兼容性
目录
概述
本指南全面介绍如何编写能在 Windows、macOS 和 Linux 上无缝运行的代码。内容涵盖文件路径处理、环境检测、平台特定功能和测试策略。
适用场景
- 为多个操作系统构建应用程序
- 处理文件系统操作
- 管理平台特定依赖项
- 检测操作系统和架构
- 使用环境变量
- 构建跨平台 CLI 工具
- 处理换行符和字符编码
- 管理平台特定的构建流程
快速开始
最简可运行示例:
// ❌ BAD: Hardcoded paths with platform-specific separators
const configPath = "C:\\Users\\user\\config.json"; // Windows only
const dataPath = "/home/user/data.txt"; // Unix only
// ✅ GOOD: Use path module
import path from "path";
import os from "os";
// Platform-independent path construction
const configPath = path.join(os.homedir(), "config", "app.json");
const dataPath = path.join(process.cwd(), "data", "users.txt");
// Resolve relative paths
const absolutePath = path.resolve("./config/settings.json");
// Get path components
const dirname = path.dirname("/path/to/file.txt"); // '/path/to'
const basename = path.basename("/path/to/file.txt"); // 'file.txt'
const extname = path.extname("/path/to/file.txt"); // '.txt'
// Normalize paths (handle .. and .)
const normalized = path.normalize("/path/to/../file.txt"); // '/path/file.txt'
参考指南
references/ 目录中的详细实现:
| 指南 | 内容 |
|---|---|
| 文件路径处理 | 文件路径处理 |
| 平台检测 | 平台检测 |
| 换行符 | 换行符 |
| 环境变量 | 环境变量 |
| Shell 命令 | Shell 命令 |
| 文件权限 | 文件权限 |
| 进程管理 | 进程管理 |
| 平台特定依赖项 | 平台特定依赖项 |
| 跨平台测试 | 跨平台测试 |
| 字符编码 | 字符编码 |
| 构建配置 | 构建配置 |
最佳实践
✅ 应该
- 使用 path.join() 或 path.resolve() 处理路径
- 使用 os.EOL 表示换行符
- 在需要时于运行时检测平台
- 在所有目标平台上进行测试
- 对平台特定模块使用 optionalDependencies
- 妥善处理文件权限
- 对用户输入进行 Shell 转义
- 规范化文本文件中的换行符
- 默认使用 UTF-8 编码
- 记录平台特定行为
- 为平台特定功能提供回退方案
- 使用 CI/CD 在多个平台上进行测试
❌ 不应该
- 使用反斜杠或正斜杠硬编码文件路径
- 假定只有 Unix 才有的功能(信号、权限、符号链接)
- 忽略 Windows 特有的情况(盘符、UNC 路径)
- 使用平台特定命令却不提供回退方案
- 假定文件系统区分大小写
- 忽略不同的换行符
- 不经检查就使用平台特定 API
- 硬编码环境变量的访问方式
- 忽略字符编码问题
评论
支持 Markdown