vscode插件开发Api:web视图api(第一部分)

webview API允许扩展在Visual Studio Code中创建完全可自定义的视图。例如,内置的 Markdown 扩展使用 Web 视图来呈现 Markdown 预览。
Web 视图自由且强大、可用于构建超出 VS Code 本机 API 支持的复杂用户界面。
github示例项目
github示例项目2

使用注意

web视图消耗资源巨大,若能通过vscode本机Api实现功能,则尽可能不要采用此法

跟随示例来学习web视图

示例的git地址

web视图的基础知识

创建一个命令来开我们的web视图

再package.json中的 contributes字段下,注册一个命令,如下图:



其中catCoding.start是我们实际关联的命令。下面两个字段是命令的名字和描述

创建web视图本体

在extension.ts中写入以下内容


import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
  context.subscriptions.push(
    vscode.commands.registerCommand('catCoding.start', () => {
      // Create and show a new webview
      const panel = vscode.window.createWebviewPanel(
        'catCoding', // Identifies the type of the webview. Used internally
        'Cat Coding', // Title of the panel displayed to the user
        vscode.ViewColumn.One, // Editor column to show the new webview panel in.
        {} // Webview options. More on these later.
      );
    })
  );
}

这段代码额意思是注册一个名为catCoing.start的命令。该命令调用vscode.window.createWebviewPanel方法创建一个web视图。其第二个参数Cat Coding是标签页的名称,第三个参数表示web视图展示在哪一栏的工作区中
至此我们创建了一个新的web视图,它有标题,不过没有内容

为新的web视图注入html内容

依然是在extension.ts文件中,改为一下内容:

import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
  context.subscriptions.push(
    vscode.commands.registerCommand('catCoding.start', () => {
      // Create and show panel
      const panel = vscode.window.createWebviewPanel(
        'catCoding',
        'Cat Coding',
        vscode.ViewColumn.One,
        {}
      );

      // And set its HTML content
      panel.webview.html = getWebviewContent();
    })
  );
}

function getWebviewContent() {
  return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cat Coding</title>
</head>
<body>
    <img src="https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif" width="300" />
</body>
</html>`;
}

如上所示,html的内容添加在webViewPanel的webview.html属性当中。webview.html是一个完整的html文件的内容,主语语法哦!
我们在这里向html中添加了一张gif图:一个敲键盘的猫猫

内容修改:可以做更多

我们可以多写一些东西,使得整个页面内容更加灵活

import * as vscode from 'vscode';

const cats = {
  'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
  'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif'
};

export function activate(context: vscode.ExtensionContext) {
  context.subscriptions.push(
    vscode.commands.registerCommand('catCoding.start', () => {
      const panel = vscode.window.createWebviewPanel(
        'catCoding',
        'Cat Coding',
        vscode.ViewColumn.One,
        {}
      );

      let iteration = 0;
      const updateWebview = () => {
        const cat = iteration++ % 2 ? 'Compiling Cat' : 'Coding Cat';
        panel.title = cat;
        panel.webview.html = getWebviewContent(cat);
      };

      // Set initial content
      updateWebview();

      // And schedule updates to the content every second
      setInterval(updateWebview, 1000);
    })
  );
}

function getWebviewContent(cat: keyof typeof cats) {
  return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cat Coding</title>
</head>
<body>
    <img src="${cats[cat]}" width="300" />
</body>
</html>`;
}

上面的代码新增的内容是:每秒调用切换一次猫猫的图片
通过panel.title来修改panel的标题
通过panel.webview.html来修改页面的内容

生命周期panel.onDidDispose

web视图有自己的生命周期api。
panel.dispose方法用于关闭web视图
panel.onDidDispose用于在视图关闭时调用,使用方法如下:

    panel.onDidDispose(
        () => {
          // When the panel is closed, cancel any future updates to the webview content
          clearInterval(interval);
        },
        null,
        context.subscriptions
      );

读取当前panel是否为可见状态

当选中其他标签页时,咱们的web视图的panel.visible将会变为false

同一时刻相同web视图只允许存在一个


当前我们可以同时又多个coding Cat的web视图,这在很多时候显然是不符合用户需求的,我们可以将其改成同一时刻相同web视图只允许存在一个

import * as vscode from 'vscode';

const cats = {
  'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
  'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif'
};

export function activate(context: vscode.ExtensionContext) {
    // Track currently webview panel
    let currentPanel: vscode.WebviewPanel | undefined = undefined;
  
    context.subscriptions.push(
      vscode.commands.registerCommand('catCoding.start', () => {
        const columnToShowIn = vscode.window.activeTextEditor
          ? vscode.window.activeTextEditor.viewColumn
          : undefined;
  
        if (currentPanel) {
          // If we already have a panel, show it in the target column
          currentPanel.reveal(columnToShowIn);
        } else {
          // Otherwise, create a new panel
          currentPanel = vscode.window.createWebviewPanel(
            'catCoding',
            'Cat Coding',
            vscode.ViewColumn.One,
            {}
          );
          currentPanel.webview.html = getWebviewContent('Coding Cat');
  
          // Reset when the current panel is closed
          currentPanel.onDidDispose(
            () => {
              currentPanel = undefined;
            },
            null,
            context.subscriptions
          );
        }
      })
    );
  }

  
function getWebviewContent(cat: keyof typeof cats) {
  return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cat Coding</title>
</head>
<body>
    <img src="${cats[cat]}" width="300" />
</body>
</html>`;
}

这里用到的一个zpi是panel.reveal(),该方法用于将视图重新显示到当前的工作区
这里的columnToShowIn就是获取的当前的工作区在哪一栏

生命周期onDidChangeViewState

前面我们了解了panel.onDidDispose,下面来了解一个新的生命周期函数onDidChangeViewState
每当 Web 视图的可见性更改或将 Web 视图移动到新列时,都会触发该事件。我们的扩展可以使用此事件根据 Web 视图显示在哪一列中来更改猫:onDidChangeViewState

import * as vscode from 'vscode';


const cats = {
    'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
    'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif',
    'Testing Cat': 'https://media.giphy.com/media/3oriO0OEd9QIDdllqo/giphy.gif'
};

export function activate(context: vscode.ExtensionContext) {
    context.subscriptions.push(
        vscode.commands.registerCommand('catCoding.start', () => {
            const panel = vscode.window.createWebviewPanel(
                'catCoding',
                'Cat Coding',
                vscode.ViewColumn.One,
                {}
            );
            panel.webview.html = getWebviewContent('Coding Cat');

            // Update contents based on view state changes
            panel.onDidChangeViewState(
                e => {
                    const panel = e.webviewPanel;
                    switch (panel.viewColumn) {
                        case vscode.ViewColumn.One:
                            updateWebviewForCat(panel, 'Coding Cat');
                            return;

                        case vscode.ViewColumn.Two:
                            updateWebviewForCat(panel, 'Compiling Cat');
                            return;

                        case vscode.ViewColumn.Three:
                            updateWebviewForCat(panel, 'Testing Cat');
                            return;
                    }
                },
                null,
                context.subscriptions
            );
        })
    );
}

function updateWebviewForCat(panel: vscode.WebviewPanel, catName: keyof typeof cats) {
    panel.title = catName;
    panel.webview.html = getWebviewContent(catName);
}


function getWebviewContent(cat: keyof typeof cats) {
    return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cat Coding</title>
</head>
<body>
    <img src="${cats[cat]}" width="300" />
</body>
</html>`;
}

加载本地内容

如果你注意看了我们的代码就会发现,我们的猫猫的gif路径是用的线上路径
为什么不在文件夹中直接放几张图呢?
因为Web 视图在无法直接访问本地资源的隔离上下文中运行。
这样做是出于安全原因。
同时这意味着,为了从扩展加载图像、样式表和其他资源,或从用户的当前工作区加载任何内容,必须使用panel.webview.asWebviewUri函数将 localURI 转换为 VS Code 可用于加载本地资源子集的特殊 URI。

import * as vscode from 'vscode';
import * as path from 'path';

export function activate(context: vscode.ExtensionContext) {
  context.subscriptions.push(
    vscode.commands.registerCommand('catCoding.start', () => {
      const panel = vscode.window.createWebviewPanel(
        'catCoding',
        'Cat Coding',
        vscode.ViewColumn.One,
        {}
      );

      // Get path to resource on disk
      const onDiskPath = vscode.Uri.file(
        path.join(context.extensionPath, 'media', 'cat.gif')
      );

      // And get the special URI to use with the webview
      const catGifSrc = panel.webview.asWebviewUri(onDiskPath);

      panel.webview.html = getWebviewContent(catGifSrc);
    })
  );
}


function getWebviewContent(cat: any) {
    return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cat Coding</title>
</head>
<body>
    <img src="${cat}" width="300" />
</body>
</html>`;
}

上面的代码中onDiskPath为gif的localURI,注意其写法:
path.join(context.extensionPath, 'media', 'cat.gif')拼接路径
vscode.Uri.file获取localURI
亲测这样写也是一样的:

const onDiskPath = vscode.Uri.file(
        "/g:/vscode-extension-samples-main/vscode-extension-samples-main/webview-sample/media/cat.gif"
      );

再用panel.webview.asWebviewUri转换成vscode可识别的特殊URI,并从该位置加载gif图

注意:
默认情况下,Web 视图只能访问以下位置的资源:

  • 在扩展的安装目录中。
  • 在用户当前处于活动状态的工作区中。
    使用WebviewOptions.localResourceRoots则能够允许访问其他本地资源。

还可以始终使用数据 URI 直接在 Web 视图中嵌入资源。

控制本地资源访问:WebviewOptions.localResourceRoots

说到WebviewOptions.localResourceRoots我们需要回头看看我们创建web视图时的初始化方法:vscode.window.createWebviewPanel()当时我们介绍了前三个参数的含义,那么第四个参数为什么是个空对象呢?

其实第四个参数就是我们这里说的WebviewOptions.localResourceRoots,它控制我们的视图可以访问的本地资源,空对象表示使用默认值,也就是上述默认情况下可以访问的扩展的安装目录中和用户当前处于活动状态的工作区中。
如果按照下述设置,则表示完全隔离本地环境,不能访问任何本地资源:

const panel = vscode.window.createWebviewPanel(
        'catCoding',
        'Cat Coding',
        vscode.ViewColumn.One,
        {
            localResourceRoots: []
        }
      );

可以通过设置对象中localResourceRoots的值来使视图对某些本地资源拥有访问权限。

vscode.commands.registerCommand('catCoding.start', () => {
      const panel = vscode.window.createWebviewPanel(
        'catCoding',
        'Cat Coding',
        vscode.ViewColumn.One,
        {
            enableScripts: true,
            localResourceRoots: [
            vscode.Uri.file(path.join(context.extensionPath, "media")),
            vscode.Uri.file(vscode.env.appRoot)
        ]
    }

下片段代码段表示只从扩展中的目录加载资源

        {
          localResourceRoots: [vscode.Uri.file(path.join(context.extensionPath, 'media'))]
        }

今天先到这里

import * as vscode from 'vscode';
import * as path from 'path';

export function activate(context: vscode.ExtensionContext) {
  context.subscriptions.push(
    vscode.commands.registerCommand('catCoding.start', () => {
      const panel = vscode.window.createWebviewPanel(
        'catCoding',
        'Cat Coding',
        vscode.ViewColumn.One,
        {
            localResourceRoots: [
            vscode.Uri.file(path.join(context.extensionPath, "html")),
            vscode.Uri.file(vscode.env.appRoot)
        ]
    }
      );

      // Get path to resource on disk
      const onDiskPath = vscode.Uri.file(
        path.join(context.extensionPath, 'media', 'cat.gif')
      );
      console.log(context.extensionPath,path,path.join(context.extensionPath, 'media', 'cat.gif'),onDiskPath)
      // And get the special URI to use with the webview
      const catGifSrc = panel.webview.asWebviewUri(onDiskPath);
      
      panel.webview.html = getWebviewContent("/g:/vscode-extension-samples-main/vscode-extension-samples-main/webview-sample/media/cat.gif");
    })
  );
}


function getWebviewContent(cat: any) {
    return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cat Coding</title>
</head>
<body>
    <img src="${cat}" width="300" />
</body>
</html>`;
}

web视图的主题样式

web视图作为vscode的一部分,我们是可以让其根据vscode的皮肤来自动切换样式颜色的
VS Code 将主题分为三个类别,并向元素添加一个特殊类以指示当前主题:body

  • vscode-light 亮主题。
  • vscode-dark 暗主题。
  • vscode-high-contrast 高对比度主题。
    下面我们用一个现实例子来说明:
    ①我们在extension.ts的html里面,将body标签内容改成:
   <body>
               <img src="${catGifPath}" width="300" />
               <h1>我不应该变色</h1>
               <h1 id="lines-of-code-counter">0</h1>

               <script nonce="${nonce}" src="${scriptUri}"></script>
           </body>

②在media/vscode.css里面使用我们上面提到的技巧,根据vscode的主题,来设置id为lines-of-code-counter的标签的颜色。

body.vscode-light #lines-of-code-counter {
    color: rgb(230, 8, 174);
  }
  
  body.vscode-dark #lines-of-code-counter{
    color: rgb(239, 255, 93);
  }
  
  body.vscode-high-contrast #lines-of-code-counter {
    color: red;
  }

③效果如下:
数字会跟随vscode的主题切换,而汉字则始终保持同一颜色
【图片待上传,截图待补充】

④完整的文件内容如下
src\extension.ts

import * as vscode from 'vscode';

const cats = {
    'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
    'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif',
    'Testing Cat': 'https://media.giphy.com/media/3oriO0OEd9QIDdllqo/giphy.gif'
};

export function activate(context: vscode.ExtensionContext) {
    context.subscriptions.push(
        vscode.commands.registerCommand('catCoding.start', () => {
            CatCodingPanel.createOrShow(context.extensionUri);
        })
    );

    context.subscriptions.push(
        vscode.commands.registerCommand('catCoding.doRefactor', () => {
            if (CatCodingPanel.currentPanel) {
                CatCodingPanel.currentPanel.doRefactor();
            }
        })
    );

    if (vscode.window.registerWebviewPanelSerializer) {
        // Make sure we register a serializer in activation event
        vscode.window.registerWebviewPanelSerializer(CatCodingPanel.viewType, {
            async deserializeWebviewPanel(webviewPanel: vscode.WebviewPanel, state: any) {
                console.log(`Got state: ${state}`);
                // Reset the webview options so we use latest uri for `localResourceRoots`.
                webviewPanel.webview.options = getWebviewOptions(context.extensionUri);
                CatCodingPanel.revive(webviewPanel, context.extensionUri);
            }
        });
    }
}

function getWebviewOptions(extensionUri: vscode.Uri): vscode.WebviewOptions {
    return {
        // Enable javascript in the webview
        enableScripts: true,

        // And restrict the webview to only loading content from our extension's `media` directory.
        localResourceRoots: [vscode.Uri.joinPath(extensionUri, 'media')]
    };
}

/**
 * Manages cat coding webview panels
 */
class CatCodingPanel {
    /**
     * Track the currently panel. Only allow a single panel to exist at a time.
     */
    public static currentPanel: CatCodingPanel | undefined;

    public static readonly viewType = 'catCoding';

    private readonly _panel: vscode.WebviewPanel;
    private readonly _extensionUri: vscode.Uri;
    private _disposables: vscode.Disposable[] = [];

    public static createOrShow(extensionUri: vscode.Uri) {
        const column = vscode.window.activeTextEditor
            ? vscode.window.activeTextEditor.viewColumn
            : undefined;

        // If we already have a panel, show it.
        if (CatCodingPanel.currentPanel) {
            CatCodingPanel.currentPanel._panel.reveal(column);
            return;
        }

        // Otherwise, create a new panel.
        const panel = vscode.window.createWebviewPanel(
            CatCodingPanel.viewType,
            'Cat Coding',
            column || vscode.ViewColumn.One,
            getWebviewOptions(extensionUri),
        );

        CatCodingPanel.currentPanel = new CatCodingPanel(panel, extensionUri);
    }

    public static revive(panel: vscode.WebviewPanel, extensionUri: vscode.Uri) {
        CatCodingPanel.currentPanel = new CatCodingPanel(panel, extensionUri);
    }

    private constructor(panel: vscode.WebviewPanel, extensionUri: vscode.Uri) {
        this._panel = panel;
        this._extensionUri = extensionUri;

        // Set the webview's initial html content
        this._update();

        // Listen for when the panel is disposed
        // This happens when the user closes the panel or when the panel is closed programmatically
        this._panel.onDidDispose(() => this.dispose(), null, this._disposables);

        // Update the content based on view changes
        this._panel.onDidChangeViewState(
            e => {
                if (this._panel.visible) {
                    this._update();
                }
            },
            null,
            this._disposables
        );

        // Handle messages from the webview
        this._panel.webview.onDidReceiveMessage(
            message => {
                switch (message.command) {
                    case 'alert':
                        vscode.window.showErrorMessage(message.text);
                        return;
                }
            },
            null,
            this._disposables
        );
    }

    public doRefactor() {
        // Send a message to the webview webview.
        // You can send any JSON serializable data.
        this._panel.webview.postMessage({ command: 'refactor' });
    }

    public dispose() {
        CatCodingPanel.currentPanel = undefined;

        // Clean up our resources
        this._panel.dispose();

        while (this._disposables.length) {
            const x = this._disposables.pop();
            if (x) {
                x.dispose();
            }
        }
    }

    private _update() {
        const webview = this._panel.webview;

        // Vary the webview's content based on where it is located in the editor.
        switch (this._panel.viewColumn) {
            case vscode.ViewColumn.Two:
                this._updateForCat(webview, 'Compiling Cat');
                return;

            case vscode.ViewColumn.Three:
                this._updateForCat(webview, 'Testing Cat');
                return;

            case vscode.ViewColumn.One:
            default:
                this._updateForCat(webview, 'Coding Cat');
                return;
        }
    }

    private _updateForCat(webview: vscode.Webview, catName: keyof typeof cats) {
        this._panel.title = catName;
        this._panel.webview.html = this._getHtmlForWebview(webview, cats[catName]);
    }

    private _getHtmlForWebview(webview: vscode.Webview, catGifPath: string) {
        // Local path to main script run in the webview
        const scriptPathOnDisk = vscode.Uri.joinPath(this._extensionUri, 'media', 'main.js');

        // And the uri we use to load this script in the webview
        const scriptUri = webview.asWebviewUri(scriptPathOnDisk);

        // Local path to css styles
        const styleResetPath = vscode.Uri.joinPath(this._extensionUri, 'media', 'reset.css');
        const stylesPathMainPath = vscode.Uri.joinPath(this._extensionUri, 'media', 'vscode.css');

        // Uri to load styles into webview
        const stylesResetUri = webview.asWebviewUri(styleResetPath);
        const stylesMainUri = webview.asWebviewUri(stylesPathMainPath);

        // Use a nonce to only allow specific scripts to be run
        const nonce = getNonce();

        return `<!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">

                <!--
                    Use a content security policy to only allow loading images from https or from our extension directory,
                    and only allow scripts that have a specific nonce.
                -->
                <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src ${webview.cspSource}; img-src ${webview.cspSource} https:; script-src 'nonce-${nonce}';">

                <meta name="viewport" content="width=device-width, initial-scale=1.0">

                <link href="${stylesResetUri}" rel="stylesheet">
                <link href="${stylesMainUri}" rel="stylesheet">

                <title>Cat Coding</title>
            </head>
            <body>
                <img src="${catGifPath}" width="300" />
                <h1>我不应该变色</h1>
                <h1 id="lines-of-code-counter">0</h1>

                <script nonce="${nonce}" src="${scriptUri}"></script>
            </body>
            </html>`;
    }
}

function getNonce() {
    let text = '';
    const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (let i = 0; i < 32; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
}

media\vscode.css

:root {
    --container-padding: 20px;
    --input-padding-vertical: 6px;
    --input-padding-horizontal: 4px;
    --input-margin-vertical: 4px;
    --input-margin-horizontal: 0;
}

body {
    padding: 0 var(--container-padding);
    color: var(--vscode-foreground);
    font-size: var(--vscode-font-size);
    font-weight: var(--vscode-font-weight);
    font-family: var(--vscode-font-family);
    background-color: var(--vscode-editor-background);
}

ol,
ul {
    padding-left: var(--container-padding);
}

body > *,
form > * {
    margin-block-start: var(--input-margin-vertical);
    margin-block-end: var(--input-margin-vertical);
}

*:focus {
    outline-color: var(--vscode-focusBorder) !important;
}

a {
    color: var(--vscode-textLink-foreground);
}

a:hover,
a:active {
    color: var(--vscode-textLink-activeForeground);
}

code {
    font-size: var(--vscode-editor-font-size);
    font-family: var(--vscode-editor-font-family);
}

button {
    border: none;
    padding: var(--input-padding-vertical) var(--input-padding-horizontal);
    width: 100%;
    text-align: center;
    outline: 1px solid transparent;
    outline-offset: 2px !important;
    color: var(--vscode-button-foreground);
    background: var(--vscode-button-background);
}

button:hover {
    cursor: pointer;
    background: var(--vscode-button-hoverBackground);
}

button:focus {
    outline-color: var(--vscode-focusBorder);
}

button.secondary {
    color: var(--vscode-button-secondaryForeground);
    background: var(--vscode-button-secondaryBackground);
}

button.secondary:hover {
    background: var(--vscode-button-secondaryHoverBackground);
}

input:not([type='checkbox']),
textarea {
    display: block;
    width: 100%;
    border: none;
    font-family: var(--vscode-font-family);
    padding: var(--input-padding-vertical) var(--input-padding-horizontal);
    color: var(--vscode-input-foreground);
    outline-color: var(--vscode-input-border);
    background-color: var(--vscode-input-background);
}

input::placeholder,
textarea::placeholder {
    color: var(--vscode-input-placeholderForeground);
}

/* #lines-of-code-counter {
color: aqua;
} */

body.vscode-light #lines-of-code-counter {
    color: rgb(230, 8, 174);
  }
  
  body.vscode-dark #lines-of-code-counter{
    color: rgb(239, 255, 93);
  }
  
  body.vscode-high-contrast #lines-of-code-counter {
    color: red;
  }

CSS的其他技巧

在编程中如果想要使用和vscode主题一样的颜色,怎么获取比较快呢?
  • 使用CSS变量来获取,例如:
code {
  color: var(--vscode-editor-foreground);
}
  • 自动补全这些变量名,可以考虑使用vscode插件
除了颜色,还有字体也可以获取到:

--vscode-editor-font-family- 编辑器字体系列(来自设置)。editor.fontFamily
--vscode-editor-font-weight- 编辑器字体粗细(来自设置)。editor.fontWeight
--vscode-editor-font-size- 编辑器字体大小(来自设置)。editor.fontSize

对特定主题设置样式

如果我们不满足于只对vscode的亮、暗、高对比三种主题设置各自的样式,而是想对其各自的主题分别设置样式,例如对主题《One Dark Pro》的样式进行设计,如下:

body[data-vscode-theme-id="One Dark Pro"] {
    background: hotpink;
}

对于需要编写针对单个主题的 CSS 的特殊情况,webviews 的 body 元素具有一个名为 data 属性的数据属性,该属性存储当前活动主题的 ID。这使您可以为 Web 视图编写特定于主题的 CSS

支持的媒体格式:

音频:

  • Wav
  • Mp3
  • Ogg
  • Flac
    视频:
  • H.264
  • VP8
    注意:使用视频时,需要保证视频轨道和音频轨道都是支持的,不然的话vscode就会播放视频,但是没有声音
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,492评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,048评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,927评论 0 358
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,293评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,309评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,024评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,638评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,546评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,073评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,188评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,321评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,998评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,678评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,186评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,303评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,663评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,330评论 2 358

推荐阅读更多精彩内容