【问题标题】:How to make acquireVsCodeApi available in vscode webview [React]如何使acquireVsCodeApi在vscode webview中可用[React]
【发布时间】:2019-10-07 19:09:53
【问题描述】:

我正在尝试基于Webview 为 vscode 开发一个新的扩展,但我在将消息从客户端发布到扩展时遇到了问题。作为初学者,我使用了this repo,我正在关注这些steps from Microsoft

正如您在示例中看到的那样:

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

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

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

有没有人知道如何将acquireVsCodeApi() 与 React 或可以提供帮助的代码 sn-p 一起使用?

问候

【问题讨论】:

    标签: reactjs typescript webview visual-studio-code vscode-extensions


    【解决方案1】:

    好的,所以首先你需要将它分配给脚本中 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' });
    

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

    【讨论】:

    • 为什么你的 TS 代码中需要 JS vscode API?您可以直接访问整个 vscode API。通过该函数获取的内容仅适用于您加载到 webview 中的 JS 脚本代码。
    【解决方案2】:

    类似于@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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 2021-09-20
      • 2019-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多