8 html css visual-studio-code vscode-extensions
我正在尝试创建一个 vscode 扩展,目标是显示带有外部 html 和 css 的 webview。
加载和设置 html 可以工作,但不幸的是 css 无法加载。
创建webview,加载html并设置:
var resultPanel = vscode.window.createWebviewPanel("test", "TestWebView", vscode.ViewColumn.One, {});
fs.readFile(path.join(context.extensionPath,'src','languageMenue.html'),(err,data) => {
if(err) {console.error(err)}
resultPanel.webview.html = data;
});
Run Code Online (Sandbox Code Playgroud)
这是可行的,在 html 中,css 像这样加载:
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="theme.css">
Run Code Online (Sandbox Code Playgroud)
css 与 html 位于同一文件夹中(在我的扩展项目的 src 文件夹内)
我缺少什么?为什么CSS无法加载?
请阅读此控制对本地资源的访问
并注意localResourceRoots如下代码:
const panel = vscode.window.createWebviewPanel(
'catCoding',
'Cat Coding',
vscode.ViewColumn.One,
{
// Only allow the webview to access resources in our extension's media directory
localResourceRoots: [vscode.Uri.file(path.join(context.extensionPath, 'media'))]
}
);
Run Code Online (Sandbox Code Playgroud)
您可以将该行编辑为:
localResourceRoots: [vscode.Uri.file(path.join(context.extensionPath, 'your/relative/location/here/in/your/extension/path'))]
css要使其工作,您必须指定存储文件的绝对路径。
IE
<link rel="stylesheet" type="text/css" href="/path/to/dir/of/theme.css">
Run Code Online (Sandbox Code Playgroud)
既然vscode建议使用secure content policy,那么实现路径动态加载的方式是这样的:
<link rel="stylesheet" type="text/css" href="{{styleSrc}}">
Run Code Online (Sandbox Code Playgroud)
其中{{styleSrc}}绑定为:
const styleSrc = vscode.Uri.file(path.join(vscode.context.extensionPath, '/path/to/dir/of/theme.css')).with({ scheme: 'vscode-resource' })
Run Code Online (Sandbox Code Playgroud)
或使用asWebviewUriAPI 作为:
const onDiskPath = vscode.Uri.file(path.join(vscode.context.extensionPath, '/path/to/dir/of/theme.css'))
const styleSrc = panel.webview.asWebviewUri(onDiskPath)
Run Code Online (Sandbox Code Playgroud)
panel创建的那个在哪里vscode.window.createWebviewPanel(...)
有关更多信息,请参阅:https://code.visualstudio.com/api/extension-guides/webview#loading-local-content
| 归档时间: |
|
| 查看次数: |
12875 次 |
| 最近记录: |