![](/img/trans.png)
[英]Visual Studio Code extension development problem with typescript
[英]Use HTML files in Visual Studio Code extension development
我想知道是否可以在單獨的文件中使用 HTML、CSS 和 JavaScript 在 Visual Studio Code 中創建擴展。
我正在使用 VS Code Webview API。 我試圖創建一個文件夾並放置我的 HTML 和 CSS 文件,但它沒有用。 我現在不知道如何在擴展 GUI 上使用這些文件。 我什至嘗試使用 NodeJS readFile()
來讀取 HTML 文件,但無法讀取文件。 使用./html/file...
相對路徑不起作用。
我錯過了什么? 我對 JS、Node 和 VS Code 還很陌生……
在文檔示例中,他們將 HTML 放入這樣的字符串中:
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(vscode.commands.registerCommand('catCoding.start',
() => {
// Create and show panel
const panel = vscode.window.createWebviewPanel('catCoding', "Cat Coding",
vscode.ViewColumn.One, { });
// And set its HTML content
panel.webview.html = getWebviewContent();
}));
}
function getWebviewContent() {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cat Coding</title>
</head>
<body>
<img src="https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif" width="300" />
</body>
</html>`;
}
是否可以將 HTML 或至少 JS 和 CSS 放在一個單獨的文件中? 這種方式可以使用庫並擁有更清晰的代碼。
鏈接到文檔: VS Code Webview API
謝謝!
它對文件夾src/html/
的文件工作的方式是:
import * as path from 'path'
import * as fs from 'fs'
const filePath: vscode.Uri = vscode.Uri.file(path.join(context.extensionPath, 'src', 'html', 'file.html'));
panel.webview.html = fs.readFileSync(filePath.fsPath, 'utf8');
您可以執行以下操作:
import * as fs from 'fs';
const pathToHtml = vscode.Uri.file(
path.join(context.extensionPath, 'src','index.html')
);
const pathUri = pathToHtml.with({scheme: 'vscode-resource'});
panel.webview.html = fs.readFileSync(pathUri.fsPath,'utf8');
這里context.extensionPath
包含您的擴展的目錄。 src
是包含您的 html 文件的擴展內的文件夾。
我什至嘗試使用 NodeJS readFile() 來讀取 HTML 文件,但無法讀取文件。 使用
./html/file...
相對路徑不起作用。
事先嘗試使用context.asAbsolutePath()
方法。 它針對擴展的根目錄解析相對路徑,而不是當前工作目錄(即 VSCode 安裝目錄)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.