Vscode 使用技巧总结

发布时间: 更新时间: 总字数:3214 阅读时间:7m 作者: IP属地: 分享 复制网址

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

说明:

  • CommitGithub release 的 Git Commit Id
    • node server 下载时的 commit id 也是这个 id

使用

  • 主题和文件图标配置 左下角<轮子> -> Theme -> Color Theme/File Icon Theme

快捷键

Code -> Preference -> Keyboard Shortcuts,然后设置对应的选项,例如:

  • File: Reveal Active File in Side Bar : cmd + L 快速在左侧栏目锁定当前文件的位置
  • 跳转到函数之后跳回之前的位置
    • Ubuntu Ctrl + Alt + -
    • Mac control + -

优化配置

  • tab 转 4 个空格:点击左下角 Spaces -> Indent Using Spaces -> 4
  • 显示tab打开setting -> 在搜索框中输入 renderControlCharacters -> 勾选复选框
  • 显示空格打开setting -> 在搜索框中输入 renderWhitespace -> 勾选复选框
  • 自动删除行尾空格打开setting -> 在搜索框中输入 files.trimTrailingWhitespace -> 勾选复选框

打开调试日志

  • 运行 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

命令行

  • Windows
# 查看 status
code -s

# 打开文件夹
code .
  • Mac
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 <!-- -->

插件

https://marketplace.visualstudio.com/vscode

常用的插件:

  • 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 : 远程开发利器
  • 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?
"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

离线安装

  • 上传方式

Code/File -> Preferences -> EXTENGIONS -> 左侧栏目右上角按钮 -> Install from VSIX...

  • 命令行方式
  1. 访问 https://marketplace.visualstudio.com/vscode
  2. 搜索插件
  3. 进入插件详情页,点击 Download Extension 下载
  4. 将插件发到 vscode 的安装目录,如:C:\Microsoft VS Code\
  5. cmd 中执行安装
code --install-extension <abc>.vsix

Python 使用

  • 选择编译器:ctl + shift + p 输入:> Go: Generate Unit Tests For Function/File
  • UI界面右上角的 debug按钮 执行时,args 不生效问题
    • 原因:它是一个扩展插件,独立于 debug 系统,不会读 launch.json
    • 解决方式(三选一)参考:issues/18199issues/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",
      "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 插件(推荐)或在 settings.jsonctrl + , 输入 > 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"
    ]
}
  • 配置 .pylintrc
pylint --generate-rcfile > .pylintrc
  • 禁用示例,在 python 代码中添加
# 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 test 使用
  • VScode golang run test 时,设置方式环境变量,参考
    • Settings -> Extensions -> Go 中配置,如
      • go.testTimeout/go.testEnvFile/go.testEnvVars
      • python.envFile
    • 也可以通过 .vscode/settings.json 指定环境变量(运行测试用例时,自动注入的环境变量):
{
  "go.testEnvVars": [
    "key1": "value1",
    "key2": "value2"
  ]
}
  • vscode 安装 golang 插件后,可以直接生成测试用例,参考 gotests
    • 选择方法右键:Go: Generate Unit Tests For Function/File
    • ctl + shift + p 输入:> Python: Select Interpreter
  • gopls 是vscode-go的自动补全工具,可以在settings.json中配置,如源码提示等

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 及以上

远程容器或Linux开发

常用插件:

  • Remote-SSH: ms-vscode.remote-server
  • Dev Containers: ms-vscode-remote.remote-containers

使用 Vscode 连接 Linux/容器时的动作:

  • 在Linux/容器内,链接到 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
  • stable 插件下载地址
https://update.code.visualstudio.com/commit:<ID>/server-linux-x64/stable
  • insider 插件下载地址
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"
  ],

变种

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.jsonhttp_proxy/https_proxy 参数

左侧菜单栏 explorer 消失问题

cmd/ctl + p,输入:

> View: Reset View Locations
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数