You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

定义VSCode自定义命令时,如何获取用户输入?

实现VS Code扩展命令的用户输入与Shell执行

1. 实现用户输入功能

VS Code扩展API提供的vscode.window.showInputBox()方法,可实现和tasks.json中inputs一致的交互式输入能力,支持配置提示文本、占位符、输入校验规则等。

基础用法示例:

// 异步获取用户输入,需将命令函数标记为async
const input = await vscode.window.showInputBox({
  prompt: "请输入DC文件路径",
  placeHolder: "例如:./config.dc",
  // 输入校验逻辑,不符合要求时返回提示文本,通过则返回null
  validateInput: (value) => {
    if (!value) return "必须输入DC文件路径";
    if (!value.endsWith(".dc")) return "请输入后缀为.dc的有效文件";
    return null;
  }
});

// 用户取消输入时,input为undefined,直接终止流程
if (!input) return;

如果需要让用户从预设选项中选择(类似tasks里的pick类型input),可以用vscode.window.showQuickPick()替代:

const options = await vscode.window.showQuickPick([
  { label: "dev.dc", description: "开发环境配置" },
  { label: "prod.dc", description: "生产环境配置" }
], {
  title: "选择要验证的DC文件"
});

if (!options) return;
const selectedFile = options.label;

2. 执行Shell命令

在扩展中执行Shell命令有两种常用方式,可根据需求选择:

方式一:静默执行并获取输出(适合后台处理)

借助Node.js的child_process模块执行命令,可直接捕获输出和错误信息:

const { exec } = require('child_process');

// 注意给路径参数加引号,避免空格导致命令解析错误
exec(`daps validate "${input}"`, (error, stdout, stderr) => {
  if (error) {
    vscode.window.showErrorMessage(`验证失败:${error.message}`);
    return;
  }
  if (stderr) {
    vscode.window.showWarningMessage(`验证警告:${stderr}`);
  }
  vscode.window.showInformationMessage(`验证完成:\n${stdout}`);
});

方式二:在VS Code终端中执行(可视化执行过程)

创建专属终端运行命令,用户可直观看到执行过程:

const terminal = vscode.window.createTerminal("DAPS验证终端");
terminal.sendText(`daps validate "${input}"`);
terminal.show(); // 自动弹出终端窗口

3. 完整命令函数示例

将输入与命令执行整合后的完整代码:

const vscode = require('vscode');
const { exec } = require('child_process');

let disposable = vscode.commands.registerCommand('daps.validate.DCfile', async function () {
  // 获取用户输入
  const input = await vscode.window.showInputBox({
    prompt: "请输入DC文件路径",
    placeHolder: "例如:./config.dc",
    validateInput: (value) => {
      if (!value) return "必须输入DC文件路径";
      if (!value.endsWith(".dc")) return "请输入后缀为.dc的有效文件";
      return null;
    }
  });

  if (!input) return;

  // 执行Shell命令
  exec(`daps validate "${input}"`, (error, stdout, stderr) => {
    if (error) {
      vscode.window.showErrorMessage(`DAPS验证失败:${error.message}`);
      return;
    }
    if (stderr) {
      vscode.window.showWarningMessage(`DAPS验证警告:${stderr}`);
    }
    vscode.window.showInformationMessage(`DAPS验证成功:\n${stdout}`);
  });
});

// 务必将命令实例加入上下文订阅,确保扩展激活时生效
context.subscriptions.push(disposable);

内容的提问来源于stack exchange,提问作者Tomáš Bažant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 07:35:19