Search code examples
javascriptvisual-studio-codevscode-extensions

How to open a local (inside the extension package) file in a vscode extension


I am creating a vscode extension. I want to provide a help command which, when invoked, opens a help.md file that is provided by the extension and therefore, I assume, shipped as part of the extension package.

myext/
├── .vscode/
├── test/
├── package.json
├── extension.js
├── help.md

How can I get a reference to the extension package content and open file help.md in the editor where the extension is running?


Solution

  • You can get the path to any file in your extension using the extension context. Here's a function I use in my extension to determine the absolute path to files I want to load:

    /**
     * Returns the absolute path to a file located in our misc folder.
     *
     * @param file The base file name.
     * @param context The context of this extension to get its path regardless where it is installed.
     * @param webview When given format the path for use in this webview.
     */
    public static getMiscPath(file: string, context: ExtensionContext, webView?: Webview): string
    {
        if (webView) {
            let uri = Uri.file(context.asAbsolutePath(path.join('misc', file)));
            return webView.asWebviewUri(uri).toString();
        }
        return context.asAbsolutePath(path.join('misc', file));
    }
    

    This function determines 2 different variants of the path:

    1. w/o WebView instance: just the absolute file path on disk.
    2. with WebView instance: a web URL for use in HTML/CSS.