WebView Extension in TypeScript

╄→尐↘猪︶ㄣ 提交于 2019-12-08 13:46:43

问题


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.


回答1:


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();



回答2:


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




回答3:


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();


来源:https://stackoverflow.com/questions/54135313/webview-extension-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!