【问题标题】:WebView Extension in TypeScriptTypeScript 中的 WebView 扩展
【发布时间】:2023-03-03 22:13:01
【问题描述】:

在代码示例 (catcoding) 中,支持 webview 逻辑被编写为 JavaScript 中的匿名函数,但是我想在 Typescript 中构建这个支持逻辑。

我已经厌倦了用 requireJS 将这个逻辑重现为 typescript 包,但我无法让它工作。

// This script will be run within the webview itself
// It cannot access the main VS Code APIs directly.
(function () {
  const vscode = acquireVsCodeApi();

…

}();

我希望在 TypeScript 中构建这个支持 WebView 逻辑,以便获得静态类型检查。

【问题讨论】:

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


    【解决方案1】:

    如果您使用 TypeScript 编写 webview 脚本,则必须使用 typescript 编译器或 webpack 将它们编译为 JavaScript(参见 github pull requests extension 示例)。

    VS Code 不包括可用于 web 视图内脚本的 VS Code api 的 TypeScript 类型,但您在 TypeScript 中要做的就是声明一个名为 acquireVsCodeApi 的全局存在:

    declare var acquireVsCodeApi: any;
    
    const vscode = acquireVsCodeApi();
    
    // Do stuff with api like getting the state
    vscode.getState();
    

    【讨论】:

    • 谢谢!这确实有助于消除不必要的噪音 :) 我还必须声明 windowdocument,但我认为 const 更适合新语法(嗯,这是固执己见):declare const window: any, document: any, acquireVsCodeApi: any;
    【解决方案2】:

    我遇到了同样的问题。我目前的 hack 涉及通过 Function 动态调用它

    const vsCodeFunction = Function(`
      // forgive me for my sins
      if (typeof acquireVsCodeApi == 'function') {
        return acquireVsCodeApi();
      } else {
        return undefined;
      }
      `);
    const vscode = vsCodeFunction();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-09
      • 2013-07-09
      • 2016-08-14
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      • 2012-09-29
      相关资源
      最近更新 更多