ViníciusPJ
ViníciusPJ

Reputation: 564

Use HTML files in Visual Studio Code extension development

I want to know if it is possible to use HTML, CSS and JavaScript in separated files to create a extension in Visual Studio Code.

I'm using VS Code Webview API. I tried to create a folder and put my HTML and CSS files but it didn't work. I don't now how to use these files on the extension GUI. I even tried to use NodeJS readFile() to read the HTML file but it failed to read the file. Relative path using ./html/file... didn't work.

What am I missing? I'm pretty new at JS, Node and VS Code...

In the docs example they put the HTML inside a string like this:

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>`;
}

Is it possible to put the HTML or at least the JS and CSS in a separated file? This way would be possible to use libs and have a cleaner code.

Link to the docs: VS Code Webview API

Thanks!

Upvotes: 3

Views: 6869

Answers (3)

Vin&#237;ciusPJ
Vin&#237;ciusPJ

Reputation: 564

The way it worked for a file inside the folder src/html/ was:

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');

Upvotes: 10

Shriram Bhat
Shriram Bhat

Reputation: 71

You can do as follows:

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');

Here context.extensionPath contains the directory of your extension. src is the folder inside the extension which contains your html file.

Upvotes: 4

Gama11
Gama11

Reputation: 34138

I even tried to use NodeJS readFile() to read the HTML file but it failed to read the file. Relative path using ./html/file... didn't work.

Try using the context.asAbsolutePath() method beforehand. It resolves relative paths against the root directory of your extension, rather than the current working directory (which is the VSCode installation directory).

Upvotes: 1

Related Questions