vscode.workspace.workspaceFolders返回错误。 Vscode扩展名

时间:2020-06-13 01:05:21

标签: typescript vscode-extensions

当我遇到一个不知道如何解决的错误时,我正在为vscode编写扩展。我试图创建一个脚本,在其中基于一些输入来创建文件,但是当我尝试获取新文件的路径时,它将返回错误!这是代码:

let command3 = vscode.commands.registerCommand('command-bot.createFile', () => {
    var fileName = vscode.window.showInputBox({
        placeHolder: "Name your file"
    });
    var fileExt = vscode.window.showInputBox({
        placeHolder: "What is the extention example: .py or .html"
    });
    const folderPath = vscode.workspace.workspaceFolders[0].uri.toString().split(":")[1];
            //The code above caused the error! Error: Object is possibly 'undefined'
});

1 个答案:

答案 0 :(得分:0)

workspaceFolders仅在用户打开工作区时可用,而在用户仅打开文件夹时不可用。

所以您可以尝试使用类似于下面的内容,

        let path: string;
        if (!workspace.workspaceFolders) {
            path = workspace.rootPath;
        } else {
            let root: WorkspaceFolder;
            if (workspace.workspaceFolders.length === 1) {
                root = workspace.workspaceFolders[0];
            } else {
                root = workspace.getWorkspaceFolder(resource);
            }

            path = root.uri.fsPath;
        }

https://github.com/vscode-restructuredtext/vscode-restructuredtext/blob/128.0.0/src/features/utils/configuration.ts#L154