【vscode】vscode插件学习(三)
前言今天继续学习制作vscode插件本地读取文件本次制作本地看小说插件。就是本地txt文件在vscode里看小说。贡献点我们要在左侧出现个图标,这里我直接整了个reactapp的logo弄来。当点击图标后激活命令,在左侧获取文件列表,点击后查看文件。"activationEvents": ["onView:myread-list"],"main": "./dist/extension.js","c
·
前言
- 今天继续学习制作vscode插件
本地读取文件
- 本次制作本地看小说插件。
- 就是本地txt文件在vscode里看小说。
贡献点
- 我们要在左侧出现个图标,这里我直接整了个reactapp的logo弄来。
- 当点击图标后激活命令,在左侧获取文件列表,点击后查看文件。
"activationEvents": [
"onView:myread-list"
],
"main": "./dist/extension.js",
"contributes": {
"commands": [
{
"command": "storyvs.helloWorld",
"title": "Hello World"
}
],
"viewsContainers": {
"activitybar": [
{
"id": "myread",
"title": "myread",
"icon": "images/logo192.png"
}
]
},
"views": {
"myread": [
{
"name": "本地列表栏",
"id": "myread-list"
}
]
}
},
代码
- 老样子,在里面注册下命令
const op = vscode.commands.registerCommand("openSelectedNovel", (args) => {
vscode.commands.executeCommand(
"vscode.open",
vscode.Uri.file(args.path)
);
});
const provider = new Provider();
const dis = vscode.window.registerTreeDataProvider("myread-list", provider);
context.subscriptions.push(dis);
context.subscriptions.push(op);
- 这个open的命令是点击左侧后打开文件的命令。
- myread-list则是点击左侧后激活的。
- 其中要传个provider,它是对TreeDataProvider的实现。这个类比较关键,它可以控制左侧显示成啥样。provider需要实现2个方法,他们返回值就是下面说的novelitem实例
function getLocalBooks(): Promise<NovelItem[]> {
const files = Fs.readdirSync(localNovelsPath);
const localnovellist: NovelItem[] = [];
files.forEach((file: string) => {
const extname = Path.extname(file).substr(1);
if (extname === "txt") {
const name = Path.basename(file, ".txt");
const path = Path.join(localNovelsPath, file);
localnovellist.push({
path,
name,
});
}
});
return Promise.resolve(localnovellist);
}
class Provider implements vscode.TreeDataProvider<NovelItem> {
// 提供单行的UI展示
getTreeItem(info: NovelItem): NovelTreeItem {
return new NovelTreeItem(info);
}
// 提供每一行的数据
getChildren(): Promise<NovelItem[]> {
return getLocalBooks();
}
}
- noveltreeitem是每一行的实例,一般是继承它默认的,然后拿我们数据对其改造
const localNovelsPath = `D:\\frontpro\\vscodego\\storyvs`;
interface NovelItem {
name: string;
path: string;
}
class NovelTreeItem extends TreeItem {
constructor(info: NovelItem) {
super(`${info.name}`);
const tips = [`名称: ${info.name}`];
// tooltip是悬浮的条提示
this.tooltip = tips.join("\r\n");
// 我们设置一下点击该行的命令,并且传参进去
this.command = {
command: "openSelectedNovel",
title: "打开该小说",
arguments: [{ name: info.name, path: info.path }],
};
}
}
- 当点击每个item实例,则触发前面已注册的command命令,这样就形成了闭环。
更多推荐
所有评论(0)