如何使 acquireVsCodeApi 在 vscode webview [React] 中可用
How to make acquireVsCodeApi available in vscode webview [React]
我正在尝试基于 Webview
为 vscode 开发一个新的扩展,但我 运行 遇到了从客户端向扩展发送消息的问题。作为初学者,我使用了 this repo and I am following these steps from Microsoft.
正如您在示例中看到的那样:
(function() {
const vscode = acquireVsCodeApi();
我的问题是,在我的 React 应用程序中,acquireVsCodeApi
就像它不存在一样。我尝试了多种方式,例如。在 componentDidMount
生命周期中,但运气不好。
This user 似乎能够 运行 但他的应用程序的某些部分丢失了所以我不清楚。
有没有人知道如何将 acquireVsCodeApi()
与 React 一起使用或可以提供帮助的代码片段?
此致
好的,所以首先你需要在脚本中将它分配给 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' });
与@Unseen 的回答类似,我所做的是创建一个 global.d.ts
文件,并在其中声明 vscode 类型。
type VSCode = {
postMessage(message: any): void;
getState(): any;
setState(state: any): void;
};
declare const vscode: VSCode;
在这种情况下,您可以在任何文件中访问 vscode。示例:https://github.com/hacker0limbo/vscode-webview-react-boilerplate/blob/master/app/global.d.ts
我正在尝试基于 Webview
为 vscode 开发一个新的扩展,但我 运行 遇到了从客户端向扩展发送消息的问题。作为初学者,我使用了 this repo and I am following these steps from Microsoft.
正如您在示例中看到的那样:
(function() {
const vscode = acquireVsCodeApi();
我的问题是,在我的 React 应用程序中,acquireVsCodeApi
就像它不存在一样。我尝试了多种方式,例如。在 componentDidMount
生命周期中,但运气不好。
This user 似乎能够 运行 但他的应用程序的某些部分丢失了所以我不清楚。
有没有人知道如何将 acquireVsCodeApi()
与 React 一起使用或可以提供帮助的代码片段?
此致
好的,所以首先你需要在脚本中将它分配给 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' });
与@Unseen 的回答类似,我所做的是创建一个 global.d.ts
文件,并在其中声明 vscode 类型。
type VSCode = {
postMessage(message: any): void;
getState(): any;
setState(state: any): void;
};
declare const vscode: VSCode;
在这种情况下,您可以在任何文件中访问 vscode。示例:https://github.com/hacker0limbo/vscode-webview-react-boilerplate/blob/master/app/global.d.ts