visual-studio-code - 使用 Svelte 使用 webviews 进行 VSCode 扩展开发挂起进程
问题描述
我正在开发一个 VSCode 扩展,它有一个由 Svelte 提供支持的侧边栏 webview,脚本正在加载但从未运行,只是挂起并在任何代码能够执行之前结束进程。这将导致 webview 崩溃,导致 VSCode 崩溃。
import * as vscode from 'vscode';
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;
}
export class SideBarProvider implements vscode.WebviewViewProvider {
_view?: vscode.WebviewView;
_doc?: vscode.TextDocument;
constructor(private readonly _extensionUri: vscode.Uri) {}
public resolveWebviewView(webviewView: vscode.WebviewView) {
this._view = webviewView;
webviewView.webview.options = {
localResourceRoots: [this._extensionUri],
};
webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);
webviewView.webview.onDidReceiveMessage(async (data) => {
console.log(data)
});
}
public revive(panel: vscode.WebviewView) {
this._view = panel;
}
private _getHtmlForWebview(webview: vscode.Webview) {
const styleResetUri = webview.asWebviewUri(
vscode.Uri.joinPath(this._extensionUri, 'styles', 'reset.css')
);
const styleVSCodeUri = webview.asWebviewUri(
vscode.Uri.joinPath(this._extensionUri, 'styles', 'vscode.css')
);
const scriptUri = webview.asWebviewUri(
vscode.Uri.joinPath(this._extensionUri, 'out', 'compiled/SideBar.js')
);
const styleMainUri = webview.asWebviewUri(
vscode.Uri.joinPath(this._extensionUri, 'out', 'compiled/out/compiledSideBar.css')
);
const getOptions = (): vscode.WebviewOptions => {
return {
enableScripts: true,
}
}
webview.options = getOptions()
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="img-src https: data:; style-src 'unsafe-inline' ${webview.cspSource}; script-src 'nonce-${nonce}'; allow-scripts: 'self'">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="${styleResetUri}" rel="stylesheet">
<link href="${styleVSCodeUri}" rel="stylesheet">
<link href="${styleMainUri}" rel="stylesheet">
<script nonce="${nonce}">
const tsvscode = acquireVsCodeApi();
</script>
</head>
<body>
<script nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>`;
}
}
此代码向 VSCode 提供 Web 视图并呈现它,这是 Svelte 代码:
<script lang="ts">
</script>
<button id="refresh">Refresh tasks</button>
<style>
</style>
解决方案
推荐阅读
- c# - Windows 的 .NET CLR 与 Linux 或 Mac OS 的不同吗?
- node.js - 有人可以建议一个单行正则表达式来解析带有 - 或 / 分隔符的字母数字和可选数字 id 吗?
- javascript - 向数组中的每个元素添加一个随机数
- python - pytest 使用 Makefile 和 make 命令
- java - 使用“类”作为数据类型是什么意思?
- java - Android Studio 错误 - 缺少类文件
- ionic-framework - 从登录页面导航到 Ionic4 中的选项卡?
- c - 无符号与有符号整数
- python-3.x - 如何更新不可更新的视图?
- python-3.x - Kaggle 内核,无法创建文件