Visual Studio 代码 Web 视图提供程序

问题描述 投票:0回答:1

明确什么是 Web 视图提供程序以及如何创建 Web 视图提供程序。

我目前正在致力于在 VSCode 中创建扩展。 补充一下,我对软件开发非常陌生,所以我的术语可能有点不正确。

我意识到创建一个 webview 视图(因此在“视图”中显示的 webview,即视图容器中的部分)与创建基本的 webview 面板有很大不同。它要求你有一个“webview提供者”,在他们的文档中没有很好地解释https://code.visualstudio.com/api/references/vscode-api#WebviewView

有人可以提供任何资源来帮助澄清什么是 Webview Provider 并创建一个 Webview Provider 吗?

visual-studio-code webview vscode-extensions vscode-webview
1个回答
0
投票

视图容器(显示侧边栏) 注册 Web 视图将使您的 VS Code 扩展具有一个可打开侧边栏的活动栏图标。 Github Copilot 就是一个例子。左侧的徽标可在主栏中打开侧栏。

如果您或其他看到这篇 StackOverflow 帖子的人需要有关视图容器的帮助,这里就是(如果您一直在尝试解决 HTML 未显示的问题,这篇文章也适合您)。

创造 - JavaScript:

function activate(context) {
  // Register the webview view
  const myWebviewProvider = new MyWebviewProvider(context.extensionUri);
  console.log("WEB VIEW PROVIDER CREATED");
  context.subscriptions.push(vscode.window.registerWebviewViewProvider('package',myWebviewProvider)); // Instead of 'package,' have your view ID
  console.log("WEB VIEW REGISTERED");
}

class MyWebviewProvider {

  constructor(extensionUri) {
    this._extensionUri = extensionUri;
  }

  resolveWebviewView(webviewView) {
    this._view = webviewView;

    // console.log("WEB VIEW *RESOLVED*");
    // // Allow scripts in the webview
    webviewView.webview.options = {
      enableScripts: true,
      localResourceRoots: [
                this._extensionUri
            ]
    };
    
    webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);

  }

  _getHtmlForWebview(webview) {
    // Webview content
    return `...`; // Type HTML here, with proper HTML boilerplate
  }
}

创建 - JSON(在 PACKAGE.JSON 中的“贡献”下):

"contributes": {
    "viewsContainers": {
      "activitybar": [
        {
          "id": "mySidebar",
          "title": "My Beautiful Sidebar extension",
          "icon": "/path/to/your_logo.svg"
        }
      ]
    },
    "views" : {
      "mySidebar" : [
        {
          "id": "myViewID",
          "name": "Some name that I want to put",
          "type": "webview"
        }
      ]
    },

重要的部分是设置

type: "webview"
,否则整个事情都不起作用(当我没有那个设置时对我不起作用)。

大量粗体和大写锁定的原因是因为在过去的三天里我一直在努力创建一个合适的网页视图,当我发现它时我想我会立即分享它。

© www.soinside.com 2019 - 2024. All rights reserved.