Windows WSL2 配置指南
Windows 用户通过 WSL2(Windows Subsystem for Linux)可以获得和 macOS/Linux 完全一致的 Claude 工具链体验。
WSL2 开发环境架构
graph TD
WIN[Windows 11/10] --> WSL2[WSL2 子系统]
WIN --> WIN_TOOLS[Windows 原生工具]
WSL2 --> UBUNTU[Ubuntu 24.04]
UBUNTU --> AI_TOOLS[AI 工具链]
UBUNTU --> DEV_TOOLS[开发工具]
AI_TOOLS --> A1[Claude Code]
AI_TOOLS --> A2[Gemini CLI]
AI_TOOLS --> A3[OpenCode]
DEV_TOOLS --> D1[Node.js / Python]
DEV_TOOLS --> D2[Git]
DEV_TOOLS --> D3[Docker]
WIN_TOOLS --> W1[VS Code + WSL 扩展]
WIN_TOOLS --> W2[Windows Terminal]
WIN_TOOLS --> W3[Docker Desktop]
WSL2 -->|无缝集成| WIN_TOOLS
style WSL2 fill:#c8e6c9,stroke:#388e3c,stroke-width:2px
style AI_TOOLS fill:#e3f2fd,stroke:#1565c0,stroke-width:2px
WSL2 + AI 工具完整安装
# === 第一步:以管理员身份在 PowerShell 执行 ===
# 启用 WSL2
wsl --install -d Ubuntu-24.04
# 重启后继续
wsl --set-default-version 2
wsl --set-default Ubuntu-24.04
# 安装 Windows Terminal(现代终端)
winget install Microsoft.WindowsTerminal
# 安装 VS Code
winget install Microsoft.VisualStudioCode
# === 第二步:在 WSL2 Ubuntu 中执行 ===
# 打开 Windows Terminal → 选择 Ubuntu
#!/usr/bin/env bash
# wsl2-ai-setup.sh — WSL2 AI 工具链一键配置
set -euo pipefail
echo "🐧 WSL2 AI 开发环境配置开始..."
# ── 系统更新 ────────────────────────────────────────
sudo apt-get update && sudo apt-get upgrade -y
sudo apt-get install -y curl wget git build-essential jq unzip
# ── Node.js(通过 nvm)───────────────────────────────
echo "📦 安装 Node.js..."
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
export NVM_DIR="$HOME/.nvm"
source "$NVM_DIR/nvm.sh"
nvm install --lts && nvm use --lts
# ── Python 3.12 ──────────────────────────────────────
echo "🐍 安装 Python..."
sudo apt-get install -y python3.12 python3.12-pip python3.12-venv
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.12 1
# ── AI 工具链 ────────────────────────────────────────
echo "🤖 安装 AI 工具..."
npm install -g @anthropic-ai/claude-code
npm install -g @google/gemini-cli
npm install -g opencode-ai
# ── Docker(WSL2 原生 Docker,无需 Docker Desktop)──────
echo "🐳 安装 Docker..."
curl -fsSL https://get.docker.com | sh
sudo usermod -aG docker "$USER"
sudo service docker start
# ── Shell 配置 ───────────────────────────────────────
cat >> ~/.bashrc << 'BASHCONFIG'
# AI 工具 Alias
alias cc='claude'
alias gc='gemini'
alias oc='opencode'
# AI 快速函数
ai-review() { git diff HEAD | claude -p "审查这次代码变更:"; }
ai-explain() { claude -p "解释这段代码:" < "$1"; }
ai-fix() { claude -p "修复 bug:" < "$1"; }
# 访问 Windows 文件系统
alias winhome="cd /mnt/c/Users/$USER"
alias windesktop="cd /mnt/c/Users/$USER/Desktop"
# 环境变量
export ANTHROPIC_API_KEY="" # 填入你的 Claude API Key
export GEMINI_API_KEY="" # 填入你的 Gemini API Key
# nvm 配置
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && source "$NVM_DIR/nvm.sh"
BASHCONFIG
source ~/.bashrc
echo "✅ WSL2 AI 环境配置完成!"
"""
WSL2 环境验证与配置诊断
解决 Windows 用户常见问题
"""
import subprocess
import os
import platform
from dataclasses import dataclass
@dataclass
class WSL2Issue:
"""常见 WSL2 问题及解决方案"""
symptom: str
cause: str
solution: str
command: str = ""
class WSL2TroubleshootGuide:
"""WSL2 常见问题排查指南"""
COMMON_ISSUES = [
WSL2Issue(
symptom="claude: command not found",
cause="npm 全局包路径未加入 PATH",
solution="将 npm 全局路径加入 .bashrc",
command='echo \'export PATH="$PATH:$(npm root -g)/../.bin"\' >> ~/.bashrc && source ~/.bashrc',
),
WSL2Issue(
symptom="网络超时,无法连接 API",
cause="WSL2 代理配置问题",
solution="配置 WSL2 使用 Windows 代理",
command="""# 在 ~/.bashrc 添加:
host_ip=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2}')
export http_proxy="http://$host_ip:7890"
export https_proxy="http://$host_ip:7890"
# 7890 改为你的代理端口""",
),
WSL2Issue(
symptom="文件权限错误(NTFS 挂载)",
cause="Windows 文件系统权限与 Linux 不兼容",
solution="工作文件放在 WSL2 home 目录,不要放在 /mnt/c/",
command="cp -r /mnt/c/Users/$USER/project ~/project",
),
WSL2Issue(
symptom="VS Code 无法连接 WSL2",
cause="未安装 VS Code WSL 扩展",
solution="安装 Remote - WSL 扩展后重连",
command='code --install-extension ms-vscode-remote.remote-wsl',
),
WSL2Issue(
symptom="内存占用过高(WSL2 吃内存)",
cause="默认 WSL2 会占用 50% 物理内存",
solution="创建 .wslconfig 限制内存",
command=r"""# 在 Windows: C:\Users\{你的用户名}\.wslconfig
[wsl2]
memory=4GB
processors=4
swap=2GB""",
),
WSL2Issue(
symptom="Docker 在 WSL2 运行慢",
cause="Bind mount 跨文件系统性能差",
solution="使用 Docker volume 替代 bind mount",
command="docker run -v mydata:/data myapp # 使用 volume,不用 -v /mnt/c/...",
),
]
PERFORMANCE_TIPS = {
"文件 I/O 最优位置": "~/(WSL2 原生 ext4),避免 /mnt/c/(NTFS,慢 10 倍)",
"网络访问": "localhost 在 WSL2 内直接可用,Windows 侧用 127.0.0.1",
"GPU 加速": "WSL2 支持 CUDA(需要 NVIDIA 驱动),Ollama 可用 GPU",
"内存配置": "在 .wslconfig 中限制为物理内存的 50%,避免 Windows 卡顿",
"终端推荐": "Windows Terminal + Ubuntu tab,比 CMD/PowerShell 好用 100 倍",
}
WINDOWS_NATIVE_COMPLEMENT = {
"Claude Chat": "浏览器访问 claude.ai(Windows 原生,无需 WSL2)",
"Git GUI": "GitHub Desktop 或 Fork(Windows)+ git CLI(WSL2)",
"API 测试": "Postman 或 Insomnia(Windows 原生)",
"数据库 GUI": "DBeaver 或 TablePlus(Windows 原生,连接 WSL2 内的 DB)",
"文件管理": "Windows Explorer 访问 WSL2 文件:地址栏输入 \\\\wsl$\\Ubuntu",
}
@classmethod
def print_guide(cls):
print("=== WSL2 AI 环境常见问题排查 ===\n")
for issue in cls.COMMON_ISSUES[:4]: # 展示前4个
print(f"❌ 症状: {issue.symptom}")
print(f" 原因: {issue.cause}")
print(f" 解决: {issue.solution}")
if issue.command:
cmd_preview = issue.command.split('\n')[0][:60]
print(f" 命令: {cmd_preview}...")
print()
print("=== 性能优化提示 ===\n")
for tip, detail in cls.PERFORMANCE_TIPS.items():
print(f" 💡 {tip}: {detail}")
print("\n=== Windows 原生工具互补 ===\n")
for tool, usage in cls.WINDOWS_NATIVE_COMPLEMENT.items():
print(f" {tool}: {usage}")
def check_wsl2_environment():
"""检测当前环境"""
is_wsl = "microsoft" in platform.uname().release.lower()
print("=== 环境检测 ===\n")
print(f" 运行环境: {'WSL2' if is_wsl else '原生 Linux/macOS'}")
print(f" 系统: {platform.system()} {platform.release()}")
tools = [
("claude", "Claude Code"),
("gemini", "Gemini CLI"),
("node", "Node.js"),
("python3", "Python"),
("docker", "Docker"),
]
print("\n 工具检测:")
for cmd, name in tools:
try:
result = subprocess.run([cmd, "--version"], capture_output=True, timeout=3)
status = "✅" if result.returncode == 0 else "❌"
except (FileNotFoundError, subprocess.TimeoutExpired):
status = "❌"
print(f" {status} {name}")
check_wsl2_environment()
WSL2TroubleshootGuide.print_guide()
WSL2 vs 原生 Linux 关键差异
| 特性 | WSL2 | 原生 Linux |
|---|---|---|
| 文件系统性能 | /home 快,/mnt/c 慢 | 全部快 |
| GPU 支持 | ✅ CUDA via WSL2 | ✅ 完整支持 |
| 网络配置 | 需要代理额外配置 | 直接配置 |
| Docker | 推荐 WSL2 原生 Docker | 原生安装 |
| 开机时间 | ~2 秒 | ~1 秒 |
| 与 Windows 互通 | ✅ 无缝文件共享 | ❌ 双系统切换 |
行动清单
- [ ] 以管理员身份运行
wsl --install -d Ubuntu-24.04,重启完成 WSL2 安装 - [ ] 在 WSL2 中执行安装脚本,安装 Claude Code + Gemini CLI
- [ ] 安装 VS Code Remote-WSL 扩展,用
code .在 WSL2 中打开项目 - [ ] 创建
.wslconfig限制内存为 4GB(防止 Windows 卡顿) - [ ] 配置代理(如需要):将 Windows 代理设置同步到 WSL2
.bashrc - [ ] 测试完整工作流:在 WSL2 中打开一个 Python 项目,用 Claude Code 实现一个小功能
下一节:03-iOS与Android移动端策略 — 在手机上随时使用 Claude 的最优方案。