vscode本身不运行haskell代码,真正执行依赖runhaskell、ghci或构建后的可执行文件;需确保ghc/hls已安装且path正确、项目含.cabal或stack.yaml、tasks.json配置准确,否则f5或ctrl+shift+b必失败。

VSCode 本身不运行 Haskell 代码,runhaskell、ghc 或 stack run 才是真正执行的命令;插件只负责调用它们——装错工具链、PATH 没生效、或 tasks.json 配错路径,点“运行”就必然失败。
为什么 F5 调试或 Ctrl+Shift+B 运行没反应
根本不是插件问题,而是 VSCode 找不到可执行的运行时工具。常见现象包括:Cannot find runtime 'ghc' in PATH、Command 'runhaskell' not found、F5 灰色不可用、终端里能跑但 VSCode 里报错。
- 在 VSCode 集成终端中直接运行
runhaskell Main.hs,如果报command not found,说明系统级工具链缺失或 PATH 未生效 -
ghcup安装的runhaskell默认在~/.ghcup/bin/(macOS/Linux)或C:ghcupin(Windows),但 VSCode 启动时可能读不到该路径(尤其 Windows PowerShell 不自动加载$env:PATH) - 别依赖插件“自动发现”——Haskell 插件(如
haskell.haskell)不提供运行能力,F5 调试必须手动配launch.json,一键运行必须配tasks.json
怎么配一个可靠的一键运行 task
最轻量、兼容单文件和项目的方式:用 tasks.json 直接调用 runhaskell,不依赖 .cabal 或 stack.yaml。
- 按
Cmd+Shift+P(macOS)或Ctrl+Shift+P(Windows/Linux),输入Tasks: Configure Task→Create tasks.json from template→Others - 替换内容为:
{
"version": "2.0.0",
"tasks": [
{
"label": "Run Haskell File",
"type": "shell",
"command": "runhaskell",
"args": ["${file}"],
"group": "build",
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared",
"showReuseMessage": true,
"clear": true
},
"problemMatcher": []
}
]
}
- 如果
runhaskell不在 PATH 中,把"command"改成绝对路径,例如:/home/username/.ghcup/bin/runhaskell或C:\ghcup\bin\runhaskell.exe - 保存后,按
Cmd+Shift+B即可运行当前打开的.hs文件
调试(F5)必须配 launch.json 且禁用优化
HLS 提供类型检查,但调试靠的是 VSCode 的调试器 + CodeLLDB(仅限 macOS/Linux)或 cppvsdbg(Windows),且 GHC 编译产物必须带调试信息。
- 先装插件:
CodeLLDB(macOS/Linux)或C/C++(Windows),否则 F5 无调试适配器 - 确保项目已构建过:
cabal build或stack build,生成带符号的可执行文件(如dist-newstyle/build/.../x86_64-linux/ghc-9.6.4/myproj-0.1.0/x/myproj/build/myproj/myproj) -
launch.json中关键项:
{
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Debug Haskell",
"program": "${workspaceFolder}/dist-newstyle/build/.../myproj",
"args": [],
"stopOnEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "lldb"
}
]
}
- 务必在
.cabal或stack.yaml中关闭优化:ghc-options: -O0 -g,否则断点失效、变量不可见 - 不要试图调试未构建的单个
Main.hs——GHC 不支持从源码直接调试,必须经构建生成可执行文件
容易被忽略的 PATH 和工作区信任问题
即使 which runhaskell 在终端返回正确路径,VSCode 仍可能找不到它,原因往往藏在环境继承和安全策略里。
- macOS:VSCode 启动方式影响 PATH。用命令行
code .打开,而非桌面图标双击,否则不会加载 shell 的~/.zshrc或~/.bash_profile - Windows:PowerShell 默认执行策略会拦截
haskell-language-server-wrapper.exe启动,临时运行Set-ExecutionPolicy RemoteSigned -Scope CurrentUser可解 - VSCode 工作区若被标记为“不受信任”,所有自动任务(包括
tasks.json)默认禁用,右下角会有黄色提示条,点击“Trust this workspace”才能启用 -
ghcup安装时勾选“自动写入 PATH”未必生效——检查~/.ghcup/env是否被 shell 配置文件 source,Windows 用户还要确认系统环境变量是否包含C:ghcupin











