VS代码扩展 - 获取完整路径

JM.*_*tez 8 javascript file-properties typescript visual-studio-code

我正在为VS Code编写一个插件,我需要知道调用扩展的文件的路径,如果它是从编辑器上下文菜单或资源管理器上下文菜单调用的,或者用户只需键入扩展命令.

function activate(context){
    // get full path of the file somehow
}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Meh*_*hdi 9

您可以调用vscode窗口属性来检索文件路径或名称,具体取决于您要查找的内容.这将为您提供执行命令时在当前选项卡中打开的文件的名称.如果从资源管理器上下文调用,我不知道它是如何工作的.

var vscode = require("vscode");
var path = require("path");
function activate(context) {
   var currentlyOpenTabfilePath = vscode.window.activeTextEditor.document.fileName;
   var currentlyOpenTabfileName = path.basename(currentlyOpenTabfilePath);
   //...
}
Run Code Online (Sandbox Code Playgroud)


Bin*_*abs 9

如果打开文件夹,则可以获取workspace变量。

let folderName = vscode.workspace.name; // get the open folder name
let folderPath = vscode.workspace.rootPath; // get the open folder path
Run Code Online (Sandbox Code Playgroud)

可以从VS Code API获得更多详细信息

  • rootPath 已弃用。我认为您可以使用以下方式获取路径: vscode.workspace.workspaceFolders[0].uri.fsPath (5认同)

mar*_*tti 7

下面是vscode在windows中返回的各种路径的示例:

扩展路径:

vscode.extensions.getExtension('extension.id').extensionUri.path
> /c:/Users/name/GitHub/extensionFolder 
vscode.extensions.getExtension('extension.id').extensionUri.fsPath
> c:\Users\name\GitHub\extensionFolder
Run Code Online (Sandbox Code Playgroud)

当前文件夹:

vscode.workspace.workspaceFolders[0].uri.path
> /c:/Users/name/Documents/Notes 
vscode.workspace.workspaceFolders[0].uri.fsPath
> c:\Users\name\Documents\Notes 
Run Code Online (Sandbox Code Playgroud)

当前编辑器文件:

vscode.window.activeTextEditor.document.uri.path
> /c:/Users/name/Documents/Notes/temp.md 
vscode.window.activeTextEditor.document.uri.fsPath
> c:\Users\name\Documents\Notes\temp.md 
Run Code Online (Sandbox Code Playgroud)

请注意path,并fsPath引用同一文件夹。fsPath 以适合操作系统的形式提供路径。


小智 6

import * as vscode from "vscode";
import * as fs from "fs";   

var currentlyOpenTabfilePath = vscode.window.activeTextEditor?.document.uri.fsPath;
Run Code Online (Sandbox Code Playgroud)

以上代码用于查找当前在vscode上激活的文件路径。

vscode.window.activeTextEditor获取编辑器的引用并document.uri.fsPath以字符串格式返回该文件的路径