The VS Code Extension Engineer builds extensions that improve developer workflows. The VS Code API surface is large - most extensions need only commands, decorations, and a webview. Start with the smallest surface that solves the problem; add more API surface only when the use case requires it.
Extension Structure
// src/extension.ts - entry point
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
// Register a command
context.subscriptions.push(
vscode.commands.registerCommand('myextension.doSomething', async () => {
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showWarningMessage('No active editor');
return;
}
const selection = editor.selection;
const text = editor.document.getText(selection);
// Show progress for async work
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: 'Processing...',
cancellable: false,
}, async (progress) => {
progress.report({ message: 'Analysing code...' });
const result = await analyseCode(text);
await editor.edit(editBuilder => {
editBuilder.replace(selection, result);
});
});
})
);
}
export function deactivate() {}
WebviewPanel (Custom UI)
function openWebview(context: vscode.ExtensionContext) {
const panel = vscode.window.createWebviewPanel(
'myextension.panel',
'My Panel',
vscode.ViewColumn.Beside,
{
enableScripts: true,
localResourceRoots: [context.extensionUri],
retainContextWhenHidden: true, // Keep state when panel is hidden
}
);
panel.webview.html = `
<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'nonce-abc123';"></head>
<body>
<button id="btn">Send message to extension</button>
<script nonce="abc123">
const vscode = acquireVsCodeApi();
document.getElementById('btn').onclick = () => {
vscode.postMessage({ type: 'action', payload: 'hello' });
};
</script>
</body>
</html>
`;
// Receive messages from webview
panel.webview.onDidReceiveMessage(msg => {
if (msg.type === 'action') { /* handle */ }
});
// Send to webview
panel.webview.postMessage({ type: 'update', data: { count: 42 } });
}
Diagnostics (Inline Error Highlighting)
const diagnosticCollection = vscode.languages.createDiagnosticCollection('myextension');
function updateDiagnostics(document: vscode.TextDocument) {
const diagnostics: vscode.Diagnostic[] = [];
// Example: flag TODO comments as warnings
const text = document.getText();
const todoRegex = /TODO:/g;
let match;
while ((match = todoRegex.exec(text)) !== null) {
const pos = document.positionAt(match.index);
const range = new vscode.Range(pos, pos.translate(0, match[0].length));
diagnostics.push(new vscode.Diagnostic(
range,
'TODO comment needs resolution before merge',
vscode.DiagnosticSeverity.Warning
));
}
diagnosticCollection.set(document.uri, diagnostics);
}