使用@tomjs/vite-plugin-vscode开发模式下WebView显示空白页问题
VS Code扩展开发问题:开发模式下WebView显示空白
我正在使用@tomjs/vite-plugin-vscode结合Vue构建VS Code扩展,基于WebView Provider进行开发,参考了其Vue最简示例。目前遇到的问题是:生产模式下扩展运行正常,但开发模式中WebView显示空白页面。
环境信息
- 操作系统:Windows_NT x64 10.0.22631
- VS Code:1.94.0(内置Node.js 20.16.0)
- Vite:5.1.4
@tomjs/vite-plugin-vscode:3.0.0
配置与代码文件
vite.config.mts
import pluginVscode from '@tomjs/vite-plugin-vscode'; import pluginVue from '@vitejs/plugin-vue'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [ pluginVscode({ recommended: true, }), pluginVue({ template: { compilerOptions: { isCustomElement: tag => tag.startsWith('vscode-'), }, }, }), ], });
index.ts
import * as vscode from 'vscode'; import { createWebviewProvider } from './webview'; export function activate(context: vscode.ExtensionContext) { context.subscriptions.push( createWebviewProvider(context), ); const disposable = vscode.commands.registerCommand('oi-runner-2.focus', () => { vscode.window.showInformationMessage('Focus!'); }); context.subscriptions.push(disposable); }
webview.ts
import process from 'node:process'; import * as vscode from 'vscode'; /** * 参考官方示例的HTML生成逻辑 */ function getHtml(webview: vscode.Webview, context: vscode.ExtensionContext) { return process.env.VITE_DEV_SERVER_URL ? __getWebviewHtml__(process.env.VITE_DEV_SERVER_URL) : __getWebviewHtml__(webview, context); } class PanelProvider implements vscode.WebviewViewProvider { static readonly VIEW_TYPE = 'oi-runner-2.panel'; constructor(private _context: vscode.ExtensionContext) {} resolveWebviewView(webviewView: vscode.WebviewView) { webviewView.webview.options = { enableScripts: true, localResourceRoots: [ vscode.Uri.joinPath(this._context.extensionUri, 'dist'), ], }; webviewView.webview.html = getHtml(webviewView.webview, this._context); } } export function createWebviewProvider(context: vscode.ExtensionContext) { return vscode.window.registerWebviewViewProvider( PanelProvider.VIEW_TYPE, new PanelProvider(context), { webviewOptions: { retainContextWhenHidden: true, }, }, ); }
排查方向
- 验证开发服务器地址:在
getHtml函数中添加日志,打印process.env.VITE_DEV_SERVER_URL,确认是否获取到正确的Vite开发服务器地址(如http://localhost:5173)。 - 检查内容安全策略(CSP):查看
__getWebviewHtml__生成的HTML中的CSP规则,确保允许加载开发服务器的脚本和样式资源,比如添加script-src 'unsafe-eval' 'unsafe-inline' http://localhost:5173;。 - 调整本地资源根目录:开发模式下Vite资源未打包到
dist,可暂时移除localResourceRoots中的dist路径,或调整为开发模式的资源目录。 - 关闭Vue开发工具:在
pluginVue配置中添加devtools: false,测试是否因开发工具注入导致WebView加载异常。
内容的提问来源于stack exchange,提问作者typed-sigterm
相关产品推荐
相关产品推荐

