简体   繁体   English

TypeScript 中的 WebView 扩展

[英]WebView Extension in TypeScript

In the code example (catcoding) the backing webview logic is written as an anonymous function in JavaScript however I would like to build this backing logic in Typescript.在代码示例(catcoding)中,支持 webview 逻辑在 JavaScript 中编写为匿名函数,但是我想在 Typescript 中构建这个支持逻辑。

I have tired to reproduce this logic as a typescript package with requireJS but I can't get this to work.我已经厌倦了将此逻辑复制为带有 requireJS 的打字稿包,但我无法让它工作。

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

…

}();

I expect to build this backing WebView logic within TypeScript so that I get the static typechecking.我希望在 TypeScript 中构建这个支持 WebView 逻辑,以便我获得静态类型检查。

If you write your webview scripts in TypeScript, you must compile them to JavaScript using the typescript compiler or webpack (see the github pull requests extension for an example).如果您使用 TypeScript 编写 webview 脚本,则必须使用 typescript 编译器或 webpack 将它们编译为 JavaScript(请参阅github pull requests 扩展以获取示例)。

VS Code does not include TypeScript typings for the VS Code api available to scripts inside of webviews, but all you have to do in your TypeScript is declare that a global called acquireVsCodeApi exists: VS Code 不包括可用于 webviews 内脚本的 VS Code api 的 TypeScript 类型,但是您在 TypeScript 中要做的就是声明存在一个名为acquireVsCodeApi的全局acquireVsCodeApi

declare var acquireVsCodeApi: any;

const vscode = acquireVsCodeApi();

// Do stuff with api like getting the state
vscode.getState();

I ran into the same issue.我遇到了同样的问题。 My current hack involves calling it dynamically via Function我目前的 hack 涉及通过Function动态调用它

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

WebView 类不能转译 TS 代码,所以你必须用 JS 编写它的代码,没有办法解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM