Vscode 使用技巧总结
安装
查看版本:
Code -> About Visual Studio Code
Version: 1.55.2 (Universal)
Commit: 3c4e3df9e89829dce27b7b5c24508306b151f30d
Date: xxx
Electron: xxx
Chromium: xxx
Node.js: xxx
V8: xxx
OS: Darwin x64 22.3.0
Sandboxed: No
说明:
Commit 为 Github release 的 Git Commit Id
- node server 下载时的 commit id 也是这个 id
 
 
使用
- 主题和文件图标配置 
设置(左下角<轮子>) -> Theme -> Color Theme/File Icon Theme 
- 字体调整:
设置 -> 窗口 -> Zoom Level,一般 1、2 效果就挺大的 
快捷键
Code -> Preference -> Keyboard Shortcuts,然后设置对应的选项,例如:
- File: Reveal Active File in Side Bar : 
cmd + L 快速在左侧栏目锁定当前文件的位置 
- 跳转到函数之后跳回之前的位置
- Ubuntu 
Ctrl + Alt + - 
- Mac 
Control + - 
 
- 折叠代码
Ctrl + Shift + ] 折叠当前代码块 
Ctrl + Shift + [ 展开当前代码块 
- 折叠所有代码块
- Mac 
Cmd + K, Cmd + 0 
- Win 
Ctrl + K, Ctrl + 0 
 
- 展开所有代码块
- Mac 
Cmd + K, Cmd + J 
- Win 
Ctrl + K, Ctrl + J 
 
- 自动换行设置,通过控制 
Editor:Word Wrap 实现
- win: 
Alt + z / alt + 1/2/3/4 
- mac 
option + z 
 
 
优化配置
tab 转 4 个空格:点击左下角 Spaces -> Indent Using Spaces -> 4 
显示tab:打开setting -> 在搜索框中输入 renderControlCharacters -> 勾选复选框 
显示空格:打开setting -> 在搜索框中输入 renderWhitespace -> 勾选复选框 
自动删除行尾空格:打开setting -> 在搜索框中输入 files.trimTrailingWhitespace -> 勾选复选框 
Telemetry: Telemetry Level 关闭项 vscode 服务器发送遥测数据 
- 内存优化
search.exclude 配置忽略的目录 
files.watcherExclude 忽略文件观察目录 
files.exclude 忽略文件 
Search: Follow Symlinks 关闭软连接跟踪 
Git: Autorefresh 关闭 
 
- 打开 Chorme 浏览器 -> 设置 ->系统 ->将
启用硬件加速模式取消 
打开调试日志
- 运行 
F1 > Preferences: Configure Runtime Arguments > 回车 
- 在文件 
argv.json 中添加 "log-level": "trace" 
重启 vscode:关闭所有 vscode 代码窗口,然后打开一个新的 vscode 窗口 
- 运行 
F1 > Output: Focus on Output View 或点击菜单 View > Output 
- 下新窗口中,右上角,选择 
Extension Host channel 等,可以查看对应的日志 
说明:最终修改的文件是 ~/.vscode/argv.json
命令行
# 查看 status
code -s
# 打开文件夹
code .
code --help
# 查看 status
code status
# 打开文件夹
open . -a Visual\ Studio\ Code
# 打开文件夹,忽略 ssl cert 验证
code . --ignore-certificate-errors
Task
VSCode Task 用来实现任务自动化
- 运行 
ctrl/command + shift + p 选中对应的 tasks 就能执行 
- 使用参考
 
{
  "label": "名字",  // 界面上展示的Task标签
  "type": "shell",  // 进程 process or 终端 shell
  "command": "echo hello world",  // 执行的命令
  "args": [],  // 命令参数
  "options": {  // 运行选项,cwd(当前工作目录)、env(环境变量)和shell的值
      "cwd": "${workspaceFolder}/hack"
  },
  "dependsOn":[],  // 运行顺序
  "presentation": {  // 其他选项
      "echo": true,  // 输出
      "reveal": "always",  // 控制集成终端是否显示,always、never、silent
      "focus": true,  // 是否获得焦点
      "panel": "shared",  // 共享输出结果,shared:共享终端、dedicated 专用的终端、new 创建新的终端
      "showReuseMessage": true,  // Task在运行前,是否清除终端的输出
      "clear": false  // 运行前清屏
  }
}
Snippet 代码片段
Snippet(代码段) 本质是模板,解决重复代码反复输入问题
新代码片段方式:
- 
轮子 -> User Snippets -> New Snippets for xxx ...
 
- 
Code -> Preferences -> Configure User Snippets -> xxx
 
- 
cmd + shift + p
 
- 
代码示例,项目级别的在 .vscode/xxx.code-snippets
 
{
	"code": {
		"scope": "markdown",
		"prefix": "code",
		"body": [
			"```",
			"$1",
			"```"
		],
		"description": "code"
	},
}
参数说明:
scope 代码片段语言
- 常用的有 
javascript,typescript,html,css,vue,vue-html,json,markdown等 
- 多个使用 
, 分隔 
"" 表示所有文件都生效 
 
prefix 前缀,代码片段名称,输入此名字时调用定义的代码片段 
body 一个数组,模板的主体内容,每一行一个字符串 
description 描述 
$1 生成代码后光标的初始位置
- 支持多个,按 tab 键可以在按照定义的顺序切换
 
$2, $3, ..., $n 
$0 结束位置 
 
${1: placeholders} 生成代码后光标的初始位置
1 表示光标开始的序号,字符表示生成代码后光标会直接选中字符 
 
\t 制表符 
\n 换行 
${1|one,two,three|} 占位符(Placeholders) 可以有多选值
- 使用 
, 分隔,选项的开始和结束用管道符号(|)将选项包含 
- 当插入代码片段,选择 
制表位(Tabstops) 会列出所有选项 
 
- 常用变量
 
CURRENT_YEAR 当前年(四位数)
CURRENT_MONTH 当前月
CURRENT_DATE 当前日
CURRENT_DAY_NAME_SHORT 当天的短名称(Mon)
CURRENT_HOUR 当前小时
CURRENT_MINUTE 当前分钟
CURRENT_SECOND 当前秒
TM_SELECTED_TEXT 当前选定的文本或空字符串
TM_CURRENT_LINE 当前行的内容
TM_CURRENT_WORD 光标下的单词的内容或空字符串
TM_LINE_INDEX 基于零索引的行号
TM_LINE_NUMBER 基于一索引的行号
TM_FILENAME 当前文档的文件名
TM_FILENAME_BASE 当前文档的文件名(不含后缀名)
TM_DIRECTORY 当前文档的目录
RELATIVE_FILEPATH 当前文件的相对目录
TM_FILEPATH 当前文档的完整文件路径
CLIPBOARD 剪切板里的内容
RANDOM 6位随机10进制数
RANDOM_HEX 6位16进制数
UUID 一个版本4的UUID
BLOCK_COMMENT_START 块注释开始标识,如 PHP /* 或 HTML <!--
BLOCK_COMMENT_END 块注释结束标识,如 PHP */ 或 HTML -->
LINE_COMMENT 行注释,如 PHP // 或 HTML <!-- -->
Secondary Side Bar
- press 
Ctrl+Alt+B/Cmd + Option + B or click the View > Appearance > Secondary Side Bar menu item 
插件
https://marketplace.visualstudio.com/vscode
vscode 需要访问的公网地址
- https://code.visualstudio.com/docs/setup/network
常用的插件:
 
autoDocstring
ctrl+shift+2 可以插入 python 注释 
 
Bookmarks 
Draw.io Integration : 编辑 .drawio, .dio, .drawio.svg or .drawio.png 
- git
Git Graph 
GitLens — Git supercharged 一目了然地可视化代码作者身份,无缝导航和探索 Git 仓库 
 
vscode-drawio 
EditorConfig 
ms-vscode.remote-server : 远程开发利器 
- REST API
rangav.vscode-thunder-client Thunder Client, Lightweight Rest API Client for VS Code 
humao.rest-client : REST API Client
- 在 
settings.json 中配置
15s 超时:"rest-client.timeoutinmilliseconds": 15000, 
- 全局变量 
rest-client.environmentVariables: $shared 
 
- 支持 
Option + Command + C 支持 generate code snippet 
- 问题:
Request timed out. Double-check your network connection and/or raise the timeout duration (currently set to 30000ms) as needed: 'rest-client.timeoutinmilliseconds'. Details: TimeoutError: Timeout awaiting 'request' for 30000ms. 怀疑是 SSL 证书的问题,settings.josn 中配置 SSL key? 
http.systemCertificates: true 
 
 
"rest-client.certificates": {
    "example.com": {
        "cert": "/path-of/ssl.crt",
        "key": "/path-of/ssl.key"
    }
}
### test request
POST http://localhost:8000/api/v1/echo HTTP/1.1
Content-Type: application/x-www-form-urlencoded
User-Agent: iPhone
test=1
&bundle_id=demo
&msg=123123
&token=token
### Basic Auth 1
POST http://localhost:8000/api/v1/echo HTTP/1.1
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
### Basic Auth 2
POST http://localhost:8000/api/v1/echo HTTP/1.1
Authorization: Basic username password
### Digest Auth
POST http://localhost:8000/api/v1/echo HTTP/1.1
Authorization: Digest username password
禁用 Copilot
> Chat: hidden Copilot
离线安装
Code/File -> Preferences -> EXTENGIONS -> 左侧栏目右上角按钮 -> Install from VSIX...
- 访问 https://marketplace.visualstudio.com/vscode
 
- 搜索插件
 
- 进入插件详情页,点击 
Download Extension 下载 
- 将插件发到 vscode 的安装目录,如:
C:\Microsoft VS Code\ 
- cmd 中执行安装
 
code --install-extension <abc>.vsix
Python 使用
- 选择编译器:
ctl + shift + p 输入:> Go: Generate Unit Tests For Function/File 
- UI 界面右上角的 
debug按钮 执行时,args 不生效问题
- 原因:它是一个扩展插件,独立于 debug 系统,不会读 
launch.json 
- 解决方式(三选一)参考:issues/18199、issues/139251
- 点击 UI 左边 debug 按钮,它与 debug 系统是集成的
 
- 按
F5(或菜单栏 Run -> Start Debugging) 
- 在 
launch.json 里添加 "purpose": ["debug-in-terminal"] 
 
 
launch.json
- 调试其他源码,需要配置 
"justMyCode": false 
 
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python",
      "type": "python",
      "request": "launch",
      "stopOnEntry": false,
      "pythonPath": "${config:python.pythonPath}",
      "program": "${file}",
      "console": "externalTerminal",
      "cwd": "${workspaceRoot}",
      "env": {"PYTHONPATH":"${workspaceRoot}"},
      "envFile": "${workspaceRoot}/.env",  // "envFile": "${workspaceFolder}//.vscode//.env",
      "args": [
        "--debug",
      ],
    }
  ]
}
No module named xxx
settings.json 解决 No module named xxx 问题 
{
  "terminal.integrated.env.linux": {
    "PYTHONPATH": "${workspaceFolder}/",
  },
  "terminal.integrated.env.osx": {
    "PYTHONPATH": "${workspaceFolder}/",
  }
}
或添加环境变量
export PYTHONPATH=$PYTHONPATH:<path-of-project>
或
import sys
sys.path.append('<path-of-project>')
PyLint
- 参考 PEP
 
- 依赖 
Python 插件 
- 安装 
pylint 
pip3 install pylint
# pylint: disable=missing-module-docstring
# pylint: disable=missing-class-docstring
# pylint: disable=missing-function-docstring
- 安装 
Pylint 插件(推荐)或在 settings.json(ctrl + , 输入 > settings) 中添加 
{
    // 代码检查
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true,
    // 保存 Python 文件时检查语法
    "python.linting.lintOnSave": true,
    "python.linting.pylintArgs": [
      "--disable=all",
      "--enable=warning,unreachable,duplicate-code,unused-argument",
      "--ignore=scripts",
      "--output-format=colorized",
      "--reports=n"
    ]
}
pylint --generate-rcfile > .pylintrc
# pylint: disable=missing-module-docstring
# pylint: enable=missing-module-docstring
# 禁用所有
# Pylint < 0.25
# pylint: disable-all
# 其他版本
# pylint: skip-file
或在 .pylintrc 中配置
[MESSAGES CONTROL]
disable=raw-checker-failed,
        ...,
        missing-module-docstring
Golang 使用
{
  "go.testEnvFile": "${workspaceFolder}/.env",
  "go.testEnvVars": [
    "key1": "value1",
    "key2": "value2"
  ],
	// 配置多个 golang 开发环境
	// "go.goroot"
	// "go.gopath"
}
- vscode 安装 golang 插件后,可以直接生成测试用例,参考 gotests
- 选择方法右键:
Go: Generate Unit Tests For Function/File 
ctl + shift + p 输入:> Python: Select Interpreter 
 
gopls(Go language server) 是 vscode-go 的自动补全工具,可以在 settings.json 中配置,如源码提示等 
    "gopls": {
        "ui.documentation.linkTarget": "pkg.go.dev"  // 点击 `import` 的跳转站点
    }
- golang dlv debug 在 proc.go 要 debug,在 
Run and Debug -> Breakpoints 中禁用自动添加的断点 
launch.json 指定程序入口
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch",
      "type": "go",
      "request": "launch",
      "mode": "auto",  // debug
      // "remotePath": "",
      // "port": 2345,
      // "host": "127.0.0.1",
      "program": "${workspaceFolder}/main.go",
      "cwd": "${workspaceFolder}",
      "args": [],
      "showLog": true
      "env": {
          "GOPATH":"/home/xiexianbin/.golang/dev"
      },
    }
  ]
}
说明:
- 更多参数参考
 
- program 参数:
${workspaceFolder} 工作区文件夹的根路径 
"${fileDirname}" 表示当前文件 
 
F&Q
gopls: failed to install gopls 问题,升级 go 到 1.20 及以上 
JAVA
vscode 插件
- Extension Pack for Java Java 开发插件扩展包
 
Spring Boot Extension Pack (Spring Boot 扩展包) (强烈推荐,即使你的项目不是纯 Spring Boot,它也提供了很多便利) 
# 配置 Java 运行时
# https://code.visualstudio.com/docs/java/java-project#_download-jdks
# https://code.visualstudio.com/docs/java/java-project#_configure-runtime-for-projects
Java Projects -> ... -> Configure Java Runtime
> Java: Open Project Settings
prettier 使用
- 安装 
Prettier - Code formatter 插件 
- 配置参考(
Settings -> Workspace -> Extensions -> Prettier 配置,也可直接在 .vscode/settings.json 中添加如下) 
{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescriptreact]": {  # for .tsx file
    "editor.defaultFormatter": "esbenp.prettier-vscode"
    # "editor.formatOnSave": true,
  },
  "editor.formatOnSave": true  # when format
	"prettier.printWidth": 120, // 超过最大值换行
	"prettier.tabWidth": 2, // 缩进字节数
	"prettier.useTabs": false, // 缩进不使用tab,使用空格
	"prettier.proseWrap": "preserve", // 默认值。因为使用了一些折行敏感型的渲染器(如GitHub comment)而按照markdown文本样式进行折行
	"prettier.arrowParens": "avoid", // (x) => {} 箭头函数参数只有一个时是否要有小括号。avoid:省略括号
	"prettier.bracketSpacing": true, // 在对象,数组括号与文字之间加空格 "{ foo: bar }"
	"prettier.disableLanguages": ["vue"], // 不格式化vue文件,vue文件的格式化单独设置
	"prettier.endOfLine": "auto", // 结尾是 \n \r \n\r auto
	"prettier.eslintIntegration": false, //不让prettier使用eslint的代码格式进行校验
	"prettier.htmlWhitespaceSensitivity": "ignore",
	"prettier.ignorePath": ".prettierignore", // 不使用prettier格式化的文件填写在项目的.prettierignore文件中
	"prettier.jsxBracketSameLine": false, // 在jsx中把'>' 单独放一行
	"prettier.jsxSingleQuote": false, // 在jsx中使用单引号代替双引号
	"prettier.parser": "babylon", // 格式化的解析器,默认是babylon
	"prettier.requireConfig": false, // Require a 'prettierconfig' to format prettier
	"prettier.stylelintIntegration": false, //不让prettier使用stylelint的代码格式进行校验
	"prettier.tslintIntegration": false // 不让prettier使用tslint的代码格式进行校验
	"prettier.semi": false, // 分号;true 句尾添加分号
  "prettier.singleQuote": true, // 使用单引号代替双引号
  "prettier.trailingComma": "none" // 去掉结尾的逗号;"es5", // 在对象或数组最后一个元素后面是否加逗号(在ES5中加尾逗号)
}
  "[markdown]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
    "editor.formatOnSave": true,
    "editor.renderWhitespace": "all",
    "editor.acceptSuggestionOnEnter": "off",
    "editor.unicodeHighlight.ambiguousCharacters": false,
    "editor.unicodeHighlight.invisibleCharacters": false,
    "diffEditor.ignoreTrimWhitespace": false,
    "editor.wordWrap": "on",
    "editor.quickSuggestions": {
      "comments": "off",
      "strings": "off",
      "other": "off"
    }
  }
- 格式化 typescript 项目 settings.json 配置
 
{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "[javascript]": {
    "editor.formatOnSave": true
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
}
# Markdown
# 方式一
<!-- prettier-ignore -->
Do   not    format   this
# 方式二
<!-- prettier-ignore-start -->
| MY | AWESOME | AUTO-GENERATED | TABLE |
|-|-|-|-|
| a | b | c | d |
<!-- prettier-ignore-end -->
- 不建议配置全局的 
defaultFormatter,建议通过 .vscode/settings.json 为每个项目单独配置格式化工具
- 否则会初选保存时,golang 代码无法使用 golang.go 自动格式化
 
 
  "[go]": {
    defaultFormatter": "golang.go"
  }
远程容器或 Linux 开发
常用插件:
- 
Remote-SSH: ms-vscode.remote-server
 
- 
Dev Containers: ms-vscode-remote.remote-containers
 
- 
使用 Vscode 连接 Linux/容器时的动作:
 
- 
在 Linux/容器内,新下载地址 https://vscode.download.prss.microsoft.com/
旧的链接 https://update.code.visualstudio.com/ 下载 node-server 安装包 
- 下载的命令:
wget --tries=1 --connect-timeout=7 --dns-timeout=7 -nv -O vscode-server.tar.gz https://update.code.visualstudio.com/commit:3c4e3df9e89829dce27b7b5c24508306b151f30d/server-linux-x64/stable 
- 在 Linux/容器中的日志目录:
~/.vscode-server/data/logs 
- 查看链接 
cd ~/.vscode-server/ grep "update.code.visualstudio.com" -r . 
- 查看链接到外网情况 
sudo ss -tnp | grep code 
 
- 
若被链接的 Linux/容器不能上网,会在 vscode 的节点下载安装包
- 显示的日志 
Setting up SSH Host xxx: Downloading VS Code Server locally 
- 缓存的目录 
/tmp/vsch-xiexianbin/serverCache/3c4e3df9e89829dce27b7b5c24508306b151f30d/vscode-server-linux-x64.tar.gz 
 
vsode 节点手动下载 vscode-server-linux-x64.tar.gz 脚本:
serverCachePath="/tmp/vsch-`whoami`/serverCache/`code -v | sed -n '2p'`/" url="https://vscode.cdn.azure.cn/stable/`code -v | sed -n '2p'`/vscode-server-linux-x64.tar.gz"
wget -O ${serverCachePath}/vscode-server-linux-x64.tar.gz $url
vscode-server 安装包手动下载
PS:以下部分,可以通过 OpenResty 缓存 update.code.visualstudio.com 的下载包到本地,实现加速下载。
主要介绍配置服务器端,第一次远程时会默认在服务器创建 ~/.vscode-server (正式版)或 ~/.vscode-server-insiders (insider)目录,登录服务器端,执行如下命令获取 commit-id(github Release Tag commit-id):
$ ll ~/.vscode-server/bin/
total 4
drwxr-xr-x 6 root root 4096 Apr 28 11:28 3c4e3df9e89829dce27b7b5c24508306b151f30d  # 获取commit:id
https://update.code.visualstudio.com/commit:<ID>/server-linux-x64/stable
https://update.code.visualstudio.com/commit:<ID>/server-linux-x64/insider
vscode 插件国内加速:使用 vscode.cdn.azure.cn 取代 az764295.vo.msecnd.net
wget https://vscode.cdn.azure.cn/stable/<commit-id>/<vscode-server-linux-x64.tar.gz>
示例下载地址:
https://update.code.visualstudio.com/commit:3c4e3df9e89829dce27b7b5c24508306b151f30d/server-linux-x64/stable
解析文件到服务器端 ~/.vscode-server/bin/3c4e3df9e89829dce27b7b5c24508306b151f30d/ 中:
tar -zxvf vscode-server-linux-x64.tar.gz -C /tmp
mv /tmp/vscode-server-linux-x64/* ~/.vscode-server/bin/3c4e3df9e89829dce27b7b5c24508306b151f30d/
然后重新使用 remote-ssh 登录服务器即可正常使用。
remote-ssh 默认安装插件
settings.json
  "remote.SSH.defaultExtensions": [
    "ms-python.python"
  ],
端口转发
- 点击靠近中下发方的 
雷达 图标即可配置 Forward a Port,实现容器端口的临时转发
 
变种
F&Q
remote-ssh git cli
- 使用 Remote-SSH 插件,vscode 报错:
 
> You seem to have git 1.8.3.1 installed. Code works best with git >= 2
安装最新版本的 git,CentOS 参考git 客户端安装最新的版本
XHR failed
错误日志:
error while fetching extensions.XHR failed
链接网络错误,一般由于网络代理导致,可以编辑 settings.json 中 http_proxy/https_proxy 参数
左侧菜单栏 explorer 消失问题
cmd/ctl + p,输入:
> View: Reset View Locations
git 不显示修改删除等颜色
执行命令
git config --global --add safe.directory <dir>
其他