— Tutorial — 1 min read
It's weird how there aren't enough tutorials online for building a VS Code extension. Never have I followed any documentation this thoroughly before. I'm the one who always relies on a mix of Stackoverflow and YouTube tutorials. So it took me quite some time to figure out building a VS Code extension to save snippets.
One thing I really got stuck on was adding a webview. Users wanted to see the snippets they had saved inside VS Code. I thought a tree view would be the right fit - because the documentation scares you from using the webview API as they warn you it can slow down the application. But tree view wasn't working well.
But then I noticed a friend's VS Code extension had a webview and it was working very smoothly (Metacode, if you're interested - super fast search across your codebase). So I took a risk and added a webview to my extension. And it works perfectly. No complaints (yet!) about it slowing down anyone's computer. Here's what it looks like:
So without further rambling, here's how you add a webview to a VS Code Extension:
In your package.json file, add a command to activate the webview function.
Now in your extension.ts (or extension.js) file, add the following code and function to open a web view.
Now this is pretty easy. Open your webview by typing the command in the Command Palette. In this example, that would be typing and choosing "Open webview".
Viola, your webview should open up! You can also bind this command to a keyboard shortcut using the keybindings function.
If you want to link an internal CSS stylesheet or Javascript file to the webview, you need to get the URI of those files from the context of the extension.
Add these lines of code inside the webview command:
1// Get path to resource on disk2 const onDiskPath = vscode.Uri.file(3 path.join(context.extensionPath, 'css', 'style.css')4 );5 // And get the special URI to use with the webview6 const cssURI = panel.webview.asWebviewUri(onDiskPath);
And then pass it into the HTML of the getWebviewContent() function. Like so:
1function getWebviewContent(uri) {2 return `<!DOCTYPE html>3<html lang="en">4<head>5 <meta charset="UTF-8">6 <meta name="viewport" content="width=device-width, initial-scale=1.0">7 <link rel='stylesheet' href='`+ uri + `' /> //This is the addition8 <title>Example Webview</title>9</head>10<body>11 <h1>This works!</h1>12 //Add some custom HTML here13</body>14</html>`;15}
Hope that was helpful!
Check out the Save Code extension for VS Code: https://marketplace.visualstudio.com/items?itemName=thiscodeworks.savecode