WebView Extension in TypeScript

2020-07-25 01:21发布

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.

I have tired to reproduce this logic as a typescript package with requireJS but I can't get this to work.

// 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.

3条回答
Ridiculous、
2楼-- · 2020-07-25 01:44

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).

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:

declare var acquireVsCodeApi: any;

const vscode = acquireVsCodeApi();

// Do stuff with api like getting the state
vscode.getState();
查看更多
时光不老,我们不散
3楼-- · 2020-07-25 01:45

The WebView class cannot transpile TS code, so you have to write its code in JS, no way around that.

查看更多
爷、活的狠高调
4楼-- · 2020-07-25 01:51

I ran into the same issue. My current hack involves calling it dynamically via Function

const vsCodeFunction = Function(`
  // forgive me for my sins
  if (typeof acquireVsCodeApi == 'function') {
    return acquireVsCodeApi();
  } else {
    return undefined;
  }
  `);
const vscode = vsCodeFunction();
查看更多
登录 后发表回答