前言
vscode
是一款非常优秀的编辑器,它的扩展生态也非常丰富,我们也可以通过 vscode
的扩展来提高我们的开发效率,比如 gitlens
、prettier
、eslint
等等,这些扩展都是非常优秀的,但是有时候我们需要一些特定的功能,而这些功能 vscode
并没有提供,这时候我们就需要自己动手开发一个 vscode
扩展了。于是,继上篇文章手把手教你如何写一个 vscode 扩展 后,这篇文章和大家一起实现以下功能:
remove console
删除选中文本中所有的console.(log|info|error|table)
代码- 自定义侧边栏+面板
代码仓库:arvinjun-extensions
remove console
功能
删除选中文本中所有的 console.(log|info|error|table)
代码,命令关键词:remove console
快捷键 cmd+shift+d
命令配置
在 package.json
文件 contributes
字段中添加如下配置:
json
{
"contributes": {
// 命令
"commands": [
{
"command": "general.removeLog",
"title": "remove console"
}
],
// 快捷键
"keybindings": [
{
"key": "cmd+shift+d",
"command": "general.removeLog"
}
]
},
}
命令实现
ts
import * as vscode from 'vscode';
/**
* 删除当前选中的文本中的所有 console.log
*/
const removeLog = vscode.commands.registerCommand('general.removeLog', () => {
const global = vscode.window;
// vscode 当前编辑页的编辑器实例
const editor = global.activeTextEditor;
if (!editor) {
return;
}
const document = editor.document;
// 获取用户选中的文本
let selectedText = document.getText(editor.selection);
if (!selectedText) {
global.showErrorMessage('Please select a text range!');
return;
}
// 删除选中文本中所有的 console.(log|info|error|table) 代码
selectedText = selectedText.replace(/\s+console.(log|info|error|table)\((.*)\);?/g, '');
editor.edit((editBuilder) => {
// 获取编辑实例,进行真正替换
editBuilder.replace(editor.selection, selectedText);
});
global.showInformationMessage('Remove log success!');
});
export default removeLog;
命令激活
ts
import * as vscode from 'vscode';
import removeLog from './general/removeLog';
export function activate(context: vscode.ExtensionContext) {
// 订阅命令
context.subscriptions.push(removeLog);
}
在 package.json
文件添加激活命令配置
json
{
// 激活命令
"activationEvents": [
"onCommand:general.removeLog"
],
}
自定义侧边栏+面板
当我们在 vscode
中打开一个项目时,会发现左侧有一个侧边栏,里面有很多入口,比如 文件
、搜索
、源代码管理
、扩展
等等,这些入口都是 vscode
内置的,那么我们如何自定义一个侧边栏呢?
那下面就让我们一起来实现一个自定义侧边栏吧!更多细节请参考 官方文档。
首先,我们需要在 package.json
文件 contributes
字段中添加如下配置:
注意⚠️:
viewsContainers
与views
字段必须同时存在,否则会报错views
字段的属性名与viewsContainers
的id
必须一致,否则会报错
json
{
"contributes": {
// 侧边栏
"viewsContainers": {
"activitybar": [
{
"id": "arvinjun",
"title": "arvinjun",
"icon": "images/logo.svg"
}
]
},
// 面板视图
"views": {
"arvinjun": [
{
"id": "Arvinjun-General",
"name": "通用"
},
{
"id": "Arvinjun-PackAnalysis",
"name": "包分析"
}
]
},
}
}
重写侧边栏入口
侧边栏入口需要继承 vscode.TreeDataProvider
类,重写 getTreeItem
和 getChildren
方法,具体代码如下:
ts
// 侧边栏菜单数据
const MENU_TREE_DATA = [
{
id: 'Arvinjun-General',
name: '通用',
commands: [
{
command: 'general.removeLog',
hotKey: 'cmd+shift+d',
title: 'remove console',
icon: 'remove.svg'
},
]
},
];
/**
* @description 重写侧边栏入口
*/
export class SideBarEntry implements vscode.TreeDataProvider<SideBarEntryItem> {
public id: string;
public rootSideBars: SideBarEntryItem[] = [];
public context?: vscode.ExtensionContext;
constructor(id: string, context?: vscode.ExtensionContext, rootSideBars?: SideBarEntryItem[]) {
this.id = id,
this.context = context;
this.rootSideBars = rootSideBars || [];
this.context = context;
}
// 重写父类属性
getTreeItem(element: SideBarEntryItem): vscode.TreeItem {
return element;
}
// 重写父类方法
getChildren(
element?: SideBarEntryItem
): vscode.ProviderResult<SideBarEntryItem[]> {
const commands = MENU_TREE_DATA?.find((view: { id: string; }) => view.id === this.id)?.commands;
//子节点
var childrenList: any = [];
commands?.forEach((item: TViewItem, index: number) => {
const children = new SideBarEntryItem(
item.title,
vscode.TreeItemCollapsibleState.None,
item.hotKey,
item.icon,
);
children.command = {
command: item.command,
title: '',
arguments: [], //命令接收的参数
};
childrenList[index] = children;
});
return childrenList;
}
}
重写侧边栏入口子节点
侧边栏入口子节点需要继承 vscode.TreeItem
类,重写 iconPath
和 contextValue
方法,具体代码如下:
ts
/**
* @description 重写侧边栏入口子节点
*/
export class SideBarEntryItem extends vscode.TreeItem {
constructor(
label: string,
collapsibleState: vscode.TreeItemCollapsibleState,
private hotKey?: string,
private icon?: string,
) {
super(label, collapsibleState);
this.tooltip = `${this.label}-${this.hotKey}`; // 鼠标悬停时的提示
this.description = this.hotKey ? `【快捷键: ${this.hotKey}】` : ''; // 节点描述
// 节点图标
this.iconPath = this.icon ? path.join(__dirname, "../../", "images", this.icon) : '';
}
}
注册侧边栏入口
ts
export default function (context: vscode.ExtensionContext) {
// 注册侧边栏面板
const sidebarArvinjunGeneral = new SideBarEntry('Arvinjun-General', context);
vscode.window.registerTreeDataProvider(
sidebarArvinjunGeneral.id,
sidebarArvinjunGeneral
);
};
接下来我们可以调试一下看看效果。如果不知道如何调试的话可以参考上篇文章 手把手教你如何写一个 中调试章节,这里便不再赘述!
到这里,我们就完成了一个 vscode
自定义侧边栏,如下图所示:

回顾总结
本文主要介绍了如何在 vscode
中实现自定义侧边栏及面板。与此同时,我们还实现了一个 vscode
扩展功能,该功能可以移除当前选择文本中的 console
日志,具体实现查看 arvinjun-extensions 项目。后续有其它 vscode
扩展功能实现也会在该项目中更新,欢迎大家一起交流学习。