Warm tip: This article is reproduced from serverfault.com, please click

How to give an argument to command "explorer.newFile" in Visial Studio Code extension development

发布于 2020-12-07 12:44:14

How to give an argument to command explorer.newFile in Visual Studio Code extension development? I just want to add create a file with certain name in explorer view and then open it and insert a snippet, these operations will be realized in a function .Help ^_^

Questioner
JJLin
Viewed
0
Mark 2020-12-08 06:41:33

I could certainly be wrong but I am not sure explorer.newFile will take an argument.

Nevertheless, this function will do what you want: create a file, open it, and insert an existing snippet:

async function createFileOpen() {

  const we = new vscode.WorkspaceEdit();

  const thisWorkspace = await vscode.workspace.workspaceFolders[0].uri.toString();

  // if you want it to be in some folder under the workspaceFolder: append a folder name
  // const uriBase = `${thisWorkspace}/folderName`; 
  // let newUri1 = vscode.Uri.parse(`${uriBase}/index.js`);

  // create a Uri for a file to be created
  const newUri = await vscode.Uri.parse(`${ thisWorkspace }\\myTestIndex.js`);
  
  // create an edit that will create a file
  await we.createFile(newUri, { ignoreIfExists: false, overwrite: true });

  await vscode.workspace.applyEdit(we); // actually apply the edit: in this case file creation

  await vscode.workspace.openTextDocument(newUri).then(
    async document => {      
      await vscode.window.showTextDocument(document);
      // if you are using a predefined snippet
      await vscode.commands.executeCommand('editor.action.insertSnippet', { 'name': 'My Custom Snippet Label Here'});
    });
}