如何在 vscode webview 中使用acquireVsCodeApi [React]

Uns*_*een 5 webview typescript reactjs visual-studio-code vscode-extensions

我正在尝试为基于 的 vscode 开发一个新扩展,Webview但我遇到了从客户端向扩展发布消息的问题。作为初学者,我使用了这个 repo,我正在遵循Microsoft 的这些步骤

正如您在示例中看到的,我们有:

(function() {
            const vscode = acquireVsCodeApi();
Run Code Online (Sandbox Code Playgroud)

我的问题是,在我的 React 应用程序中,acquireVsCodeApi它似乎不存在。我尝试了多种方法,例如。在componentDidMount生命周期中,但没有运气。

该用户似乎能够运行它,但他的应用程序的某些部分丢失了,所以我不清楚。

有没有人知道如何使用acquireVsCodeApi()React 或可以提供帮助的代码片段?

问候

Uns*_*een 5

好的,首先您需要将其分配给脚本中的 webview 内容中的变量,例如: https: //github.com/shinhwagk/vscode-note/blob/be2aabf2812a9b6200be971425535024440dbd88/src/panel/notesPanelView.ts#L32

然后在打字稿中,它必须是一个接口

interface vscode {
    postMessage(message: any): void;
}

declare const vscode: vscode;

const addCategory = () => () => vscode.postMessage({ command: 'add-category' });
Run Code Online (Sandbox Code Playgroud)

解决方案来自这里: https: //github.com/shinhwagk/vscode-note/blob/be2aabf2812a9b6200be971425535024440dbd88/src/webview/index.tsx#L10

  • 为什么你的TS代码中需要JS vscode API?您可以直接访问整个 vscode API。通过该函数的获取仅适用于加载到 webview 中的 JS 脚本代码。 (2认同)