VSCode扩展开发:如何让右键菜单仅在含特定扩展名文件的文件夹显示
实现VSCode扩展右键菜单仅在含特定扩展名文件的文件夹显示
你之前的配置思路存在问题,resourceFilename变量对应的是当前选中的单个资源(文件/文件夹)的名称,并非该文件夹下的文件路径,所以用正则匹配路径的方式无法生效。要实现需求,需通过自定义上下文变量判断文件夹内是否包含目标文件,具体步骤如下:
1. 在扩展主文件中添加监听逻辑
在扩展入口文件(如extension.ts或extension.js)中,监听资源管理器的选中变化,判断当前选中的文件夹是否包含.new文件,并设置自定义上下文变量:
TypeScript示例
import * as vscode from 'vscode'; import * as fs from 'fs'; import * as path from 'path'; export function activate(context: vscode.ExtensionContext) { // 监听资源管理器选中项变更 const selectionListener = vscode.window.onDidChangeSelection(() => { updateFolderContext(); }); // 初始化时执行一次判断 updateFolderContext(); context.subscriptions.push(selectionListener); } function updateFolderContext() { // 获取资源管理器中选中的项 vscode.commands.executeCommand('explorer.getSelection').then((selection: any[]) => { let hasNewFile = false; if (selection?.length > 0) { const selectedUri = selection[0]; // 确认选中的是文件夹 if (selectedUri?.fsPath && fs.statSync(selectedUri.fsPath).isDirectory()) { // 遍历文件夹,检查是否存在.new后缀的文件 hasNewFile = fs.readdirSync(selectedUri.fsPath).some(file => path.extname(file).toLowerCase() === '.new' ); } } // 设置自定义上下文变量,供菜单配置使用 vscode.commands.executeCommand('setContext', 'folderContainsNewFile', hasNewFile); }); } export function deactivate() {}
JavaScript示例
const vscode = require('vscode'); const fs = require('fs'); const path = require('path'); function activate(context) { const selectionListener = vscode.window.onDidChangeSelection(() => { updateFolderContext(); }); updateFolderContext(); context.subscriptions.push(selectionListener); } function updateFolderContext() { vscode.commands.executeCommand('explorer.getSelection').then((selection) => { let hasNewFile = false; if (selection && selection.length > 0) { const selectedUri = selection[0]; if (selectedUri?.fsPath && fs.statSync(selectedUri.fsPath).isDirectory()) { hasNewFile = fs.readdirSync(selectedUri.fsPath).some(file => path.extname(file).toLowerCase() === '.new' ); } } vscode.commands.executeCommand('setContext', 'folderContainsNewFile', hasNewFile); }); } function deactivate() {} module.exports = { activate, deactivate };
2. 修改package.json的菜单配置
在package.json的contributes/menus部分,使用自定义的上下文变量控制菜单显示:
"contributes": { "commands": [ { "command": "extensionName/my-command", "title": "你的自定义命令标题" } ], "menus": { "explorer/context": [ { "command": "extensionName/my-command", "when": "explorerResourceIsFolder && folderContainsNewFile" } ] } }
关键说明
explorerResourceIsFolder:确保菜单只在文件夹上触发folderContainsNewFile:自定义变量,仅当文件夹内存在.new文件时为true- 监听
explorer.getSelection:准确获取资源管理器中选中的文件夹,避免误判
内容的提问来源于stack exchange,提问作者heapOverflow
相关产品推荐
相关产品推荐

