Windows 上跑 npm / 脚本时最常遇到的两个问题:脚本被策略拦截,中文输出乱码。
以管理员身份打开 PowerShell
查看当前的执行策略(可选):
Get-ExecutionPolicy
# Restricted(禁止)
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
-Scope CurrentUser 只修改当前用户的策略,不影响系统其他部分,相对安全RemoteSigned 的含义:本地脚本可直接运行,从网络下载的脚本需要签名系统会提示是否更改执行策略。输入
Y然后回车。
npm -v,应该能正常显示版本号chcp
936 = GBK65001 = UTF-8chcp 65001
打开 PowerShell 配置文件:
notepad $PROFILE
如果提示路径不存在,先创建:
New-Item -ItemType File -Path $PROFILE -Force
notepad $PROFILE
写入下面这段并保存:
chcp 65001 > $null
[Console]::InputEncoding = [System.Text.UTF8Encoding]::new()
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
$OutputEncoding = [System.Text.UTF8Encoding]::new()
$PSDefaultParameterValues['*:Encoding'] = 'utf8'
重新打开 PowerShell,执行 chcp 验证是否变为 65001。
如果 VS Code 的集成终端仍乱码,检查 VS Code 设置里的
terminal.integrated.defaultProfile.windows是否指向 PowerShell 7(pwsh)而非 Windows PowerShell 5.1。