繁体   English   中英

无法使用 html 文件将 styles 应用于 VSCode Webview

[英]Can't apply styles to VSCode Webview using html file

我正在构建一个 VSCode Webview 并尝试应用一些 css。

我唯一的成功是使用以下方法

const webview = this._panel.webview;
const stylePathOnDisk = vscode.Uri.file(path.join(this._extensionPath, '/res/css/styles.css'));
const styleUri = webview.asWebviewUri(stylePathOnDisk);

webview.html = `
  <!doctype html>
  <html>
    <head>
      <link rel='stylesheet' type='text/css' href='${styleUri}'>
    </head>
    <body>
      <h1>test</h1>
    </body>
  </html>
  `

但我想将我的 html 放在一个单独的文件中,像这样使用

const htmlPathOnDisk = vscode.Uri.file(path.join(this._extensionPath, '/res/html/index.html'));
webview.html = fs.readFileSync(htmlPathOnDisk.path).toString();

但是,我不能在该 html 文件中使用${styleUri} 我也不能使用<link ref='stylesheet' type='text/css' href='{{styleUri}}> ,甚至我也不能在<head>标签中使用<style>标签(这些都不适用 css .

前两种方法(在上面的句子中)我知道我可能执行不正确,但我没想到第三种风格会失败。

有什么建议吗?

正如@Matt Bierner 所说,这是解决方案。

const htmlPathOnDisk = vscode.Uri.file(path.join(this._extensionPath, '/res/html/index.html'));
var html = fs.readFileSync(htmlPathOnDisk.path).toString();

const stylePathOnDisk = vscode.Uri.file(path.join(this._extensionPath, '/res/css/styles.css'));
const styleUri = webview.asWebviewUri(stylePathOnDisk);
html = html.replace('${styleUri}', styleUri.toString());

// continue for any other resources, e.g. scripts

webview.html = html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM