支持类 Unix 语法 `&&`:Windows 下用 PowerShell 7 优化 npm 和 VS Code

不支持 && ?

在类 Unix 系统中,&& 是常用的命令组合符,表示 前一个命令成功后再执行下一个命令。例如:

echo "第一步成功" && echo "第二步执行"

在 Windows 的默认环境中,cmd 或旧版 PowerShell 对 && 支持有限,可能会遇到脚本兼容性问题。本文教你如何通过 PowerShell 7 完全支持 &&,并让 npm 和 VS Code 使用它,从而获得类 Unix 体验。


一、安装 PowerShell 7

使用 Windows 官方包管理器 winget 快速安装:

winget install --id Microsoft.Powershell --source winget

安装完成后验证版本:

pwsh -v

默认路径:C:\Program Files\PowerShell\7\pwsh.exe

PowerShell 7 完全支持类 Unix 命令组合符 &&


二、让 npm 使用 PowerShell 7

npm 脚本默认使用系统 shell,如果是旧版 PowerShell,可能无法正确识别 &&。通过设置 script-shell 可以永久解决:

npm config set script-shell "C:\\Program Files\\PowerShell\\7\\pwsh.exe"

验证:

npm config get script-shell

测试脚本支持 &&

"scripts": {
  "test": "echo 第一条 && echo 第二条"
}

运行:

npm run test

如果输出:

第一条
第二条

说明 && 支持正常工作。


三、在 VS Code 中使用 PowerShell 7

为了在终端中直接使用 &&,需要将 VS Code 默认终端改为 PowerShell 7:

  1. 打开 VS Code 设置 (Ctrl + ,)
  2. 搜索 terminal.integrated.profiles.windows
  3. 添加配置:
"terminal.integrated.profiles.windows": {
    "PowerShell 7": {
        "path": "C:\\Program Files\\PowerShell\\7\\pwsh.exe"
    }
},
"terminal.integrated.defaultProfile.windows": "PowerShell 7"

重启 VS Code,打开终端即可直接使用:

echo "第一步" && echo "第二步"

四、总结

通过以上步骤,你在 Windows 下就能:

  • 使用 PowerShell 7 支持类 Unix 的 && 语法
  • 让 npm 脚本支持 &&
  • 在 VS Code 终端直接使用类 Unix 命令组合符

这让 Windows 开发环境更接近 Linux/macOS,提升跨平台脚本兼容性。

posted @ 2025-09-12 19:32  丘狸尾  阅读(92)  评论(0)    收藏  举报