Search code examples
reactjstypescriptwebviewvisual-studio-codevscode-extensions

How to make acquireVsCodeApi available in vscode webview [React]


I'm trying to develop a new extension for vscode based on Webview but I am running into problems with posting messages from client to extension. As a starter, I used this repo and I am following these steps from Microsoft.

As you can see in the example we have:

(function() {
            const vscode = acquireVsCodeApi();

My problem is that in my react app the acquireVsCodeApi is like it doesn't exist. I tried multiple ways eg. in componentDidMount lifecycle but no luck.

This user seems to be able to run it but parts of his app are missing so is not clear to me.

Does anyone have an idea of how to use acquireVsCodeApi() with React or a code snippet that can help?

Regards


Solution

  • Ok, so first you need to assign it into a variable in webview content in a script eg: https://github.com/shinhwagk/vscode-note/blob/be2aabf2812a9b6200be971425535024440dbd88/src/panel/notesPanelView.ts#L32

    and then in typescript, it has to be an interface

    interface vscode {
        postMessage(message: any): void;
    }
    
    declare const vscode: vscode;
    
    const addCategory = () => () => vscode.postMessage({ command: 'add-category' });
    

    Solution came from here: https://github.com/shinhwagk/vscode-note/blob/be2aabf2812a9b6200be971425535024440dbd88/src/webview/index.tsx#L10