What You’ll Learn in This Tutorial
✓ Creating extension project
✓ Registering commands
✓ Language support
✓ WebView
✓ Publishing
Step 1: Create Project
npm install -g yo generator-code
yo code
# Select:
# - New Extension (TypeScript)
# - Extension name: my-extension
# - Identifier: my-extension
Step 2: Project Structure
my-extension/
├── src/
│ └── extension.ts
├── package.json
├── tsconfig.json
└── .vscode/
└── launch.json
Step 3: Basic Extension
// src/extension.ts
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
// Register command
const disposable = vscode.commands.registerCommand(
'my-extension.helloWorld',
() => {
vscode.window.showInformationMessage('Hello World!');
}
);
context.subscriptions.push(disposable);
}
export function deactivate() {}
Step 4: package.json Configuration
{
"name": "my-extension",
"displayName": "My Extension",
"version": "0.0.1",
"engines": { "vscode": "^1.85.0" },
"activationEvents": [],
"main": "./out/extension.js",
"contributes": {
"commands": [
{
"command": "my-extension.helloWorld",
"title": "Hello World"
}
],
"keybindings": [
{
"command": "my-extension.helloWorld",
"key": "ctrl+shift+h"
}
]
}
}
Step 5: Editor Operations
vscode.commands.registerCommand('my-extension.insertDate', () => {
const editor = vscode.window.activeTextEditor;
if (!editor) return;
const date = new Date().toISOString().split('T')[0];
editor.edit((editBuilder) => {
editBuilder.insert(editor.selection.active, date);
});
});
Step 6: File Operations
// Read file
const uri = vscode.Uri.file('/path/to/file');
const content = await vscode.workspace.fs.readFile(uri);
// Write file
await vscode.workspace.fs.writeFile(uri, Buffer.from('content'));
// Search workspace files
const files = await vscode.workspace.findFiles('**/*.ts');
Step 7: WebView
vscode.commands.registerCommand('my-extension.openPanel', () => {
const panel = vscode.window.createWebviewPanel(
'myPanel',
'My Panel',
vscode.ViewColumn.One,
{ enableScripts: true }
);
panel.webview.html = `
<!DOCTYPE html>
<html>
<body>
<h1>Hello WebView</h1>
<button id="btn">Click me</button>
<script>
const vscode = acquireVsCodeApi();
document.getElementById('btn').onclick = () => {
vscode.postMessage({ type: 'click' });
};
</script>
</body>
</html>
`;
panel.webview.onDidReceiveMessage((message) => {
if (message.type === 'click') {
vscode.window.showInformationMessage('Button clicked!');
}
});
});
Step 8: Debug and Publish
# Debug
# Press F5 to launch Extension Development Host
# Build
npm run compile
# Package
npm install -g vsce
vsce package
# Publish
vsce publish
Summary
Customize your editor with VS Code extensions. Add powerful features with commands, language support, and WebView.
← Back to list