VSCode插件开发:右键点击创建一个文件夹和相应名称的文件

发布时间 2023-12-08 18:03:27作者: 乌拉小考

开发一个输入名称然后创建文件夹和相同文件名的文件
那么首先是注册右键点击事件

"contributes": {
    "commands": [
      {
        "command": "createuniappfile.createvuefile",
        "title": "Create Uniapp File"
      }
    ],
    "menus": {
      "explorer/context": [{
        "command": "createuniappfile.createvuefile",
        "group": "uniapp"
      }]
    }
  },

然后再点击之后弹出输入框让用户输入文件夹的名称,

  const inputName = await vscode.window.showInputBox();

下面是创建文件夹和文件的代码,固定写的vue文件

 // 创建文件夹和文件
    const wsedit = new vscode.WorkspaceEdit();
    const path = uri.fsPath;
    let dirPath = ""
    if (isDir(path)) {
      console.log("is dir");
      dirPath = path
    } else {
      console.log("is file");
      let index = path.lastIndexOf("/")
      dirPath = path.substring(0, index)
    }

    let filePath = `${dirPath}/${name}/${name}.vue`
    let fileUri = vscode.Uri.file(filePath);
    wsedit.createFile(fileUri, {ignoreIfExists: false});
    vscode.workspace.applyEdit(wsedit);
    vscode.window.showInformationMessage(
      `创建文件成功:${filePath}`
    );

完整代码