在VSCode中开发插件,除了使用传统的HTML、CSS和JavaScript,我们还可以利用现代的前端构建工具如Vue和Vite来构建webview页面。
在这篇文章中,我们将探讨如何使用Vue和Vite来开发VSCode插件中的webview页面。
1、创建vue项目
在vscode项目内创建vue项目
npm create vue@latest
创建后的目录如图所示
启动vue,浏览器显示的页面如下
2、打包vue
众所周知,任何框架的项目要部署到生产环境,都要打包成原始的html、js、css等静态资源,生成的文件中index.html就是项目的入口;
而webview的内容可以是普通字符串或者html模板字符串,那么只需要将vue打包出来的index.html读取转化成模板字符串即可
在vue项目目录下执行
npm run build
打包结果如下
3、创建webview
4、将vue页面挂载到webview
将html文件读取转化为模板字符串,并将html中引用资源的路径替换为webview下的路径
上一步中已经创建了一个webview,并将内容赋值为普通字符串,这一步需要将普通字符串替换为html模板字符串即可
import * as vscode from 'vscode';
const path = require('path');
const fs = require('fs');
export class DependenciesProvider implements vscode.WebviewViewProvider {
context: vscode.ExtensionContext
constructor(context: vscode.ExtensionContext) {
this.context = context
}
// 实现 resolveWebviewView 方法,用于处理 WebviewView 的创建和设置
resolveWebviewView(webviewView: vscode.WebviewView, context: vscode.WebviewViewResolveContext<unknown>, token: vscode.CancellationToken): void | Thenable<void> {
// 配置 WebviewView 的选项
webviewView.webview.options = {
enableScripts: true,
localResourceRoots: [this.context.extensionUri]
};
// 设置 WebviewView 的 HTML 内容,可以在这里指定要加载的网页内容
webviewView.webview.html = this.getHtmlForWebview(this.context, webviewView);
}
/**
* Returns html of the start page (index.html)
*/
private getHtmlForWebview(context: vscode.ExtensionContext, webviewView: vscode.WebviewView) {
const appDistPath = path.join(context.extensionPath, '/file-list-view/dist');
const indexPath = path.join(appDistPath, 'index.html');
let indexHtml = fs.readFileSync(indexPath, { encoding: 'utf8' });
const matchLinks = /(href|src)="([^"]*)"/g;
const toUri = (_: string, prefix: 'href' | 'src', link: string) => {
if (link === '#') {
return `${prefix}="${link}"`;
}
const _path = path.join(appDistPath, link);
const uri = vscode.Uri.file(_path);
return `${prefix}="${webviewView.webview['asWebviewUri'](uri)}"`;
};
indexHtml = indexHtml.replace(matchLinks, toUri);
return indexHtml;
}
}
调试vscode插件,侧边栏正常显示vue页面