can you write a vscode extension sample with eslint.
- User
can you write a vscode extension sample with eslint.
Assistant
I'll help you create a VSCode extension that integrates ESLint. Here's a sample implementation:
// extension.ts import * as path from 'path'; import * as vscode from 'vscode'; import { Linter } from 'eslint'; export function activate(context: vscode.ExtensionContext) { // Check if ESLint config exists in workspace const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; if (!workspaceFolder) return; // Create ESLint linter instance const linter = new Linter({ configFilePath: path.join(workspaceFolder.uri.fsPath, '.eslintrc.json') }); // Register linting on document save vscode.workspace.onDidSaveTextDocument(document => { if (document.languageId !== 'javascript') return; const text = document.getText(); const results = linter.verify(text, { env: { es6: true }, parserOptions: { ecmaVersion: 2022, sourceType: 'module' } }, { filename: document.fileName }); // Clear previous diagnostics vscode.languages.clearDiagnostics(document.uri); // Create new diagnostics const diagnostics: vscode.Diagnostic[] = results.map(result => { const start = document.positionAt(result.line - 1); const end = document.positionAt(result.line); return new vscode.Diagnostic( new vscode.Range(start, end), result.message, vscode.DiagnosticSeverity.Error ); }); vscode.languages.createDiagnosticCollection('eslint').set(document.uri, diagnostics); }); // Register code fix command context.subscriptions.push( vscode.commands.registerCommand('eslint.fix', async () => { const editor = vscode.window.activeTextEditor; if (!editor) return; const document = editor.document; const text = document.getText(); const fixed = linter.verifyAndFix(text, { env: { es6: true }, parserOptions: { ecmaVersion: 2022, sourceType: 'module' } }); if (fixed.output) { await editor.edit(edit => { edit.replace( new vscode.Range( document.positionAt(0), document.positionAt(text.length) ), fixed.output ); }); } }) ); }You'll need these dependencies in your
package.json:{ "name": "eslint-sample", "version": "0.0.1", "publisher": "yourname", "engines": { "vscode": "^1.75.0" }, "dependencies": { "eslint": "^8.56.0" }, "devDependencies": { "@types/vscode": "^1.75.0", "typescript": "^5.3.0" } }Key features of this extension:
- Lints JavaScript files on save
- Shows ESLint errors in the Problems panel
- Provides a command to auto-fix issues (
eslint.fix)
To use this:
- Create a new VSCode extension project using
yo code - Add the above code to
extension.ts - Install dependencies with
npm install eslint --save - Create a sample
.eslintrc.jsonin your test project - Press F5 to debug the extension
The extension will:
- Highlight ESLint errors in the editor
- Show detailed error messages in the Problems panel
- Provide a command to automatically fix ESLint issues
You can enhance this by:
- Adding more configuration options
- Supporting TypeScript
- Adding rule customization
- Implementing real-time linting
- Adding extension configuration options
Would you like me to elaborate on any specific part of the implementation?
- User
can you explain the code
Assistant
Let me break down the VSCode extension code step by step:
1. File Structure
extension.ts: Main entry point for the VSCode extensionpackage.json: Defines dependencies and metadata
2. Key Components in
extension.tsa. Activation Function
export function activate(context: vscode.ExtensionContext) { // ... main logic here ... }- Entry point when the extension is activated
- Receives a
contextobject for managing subscriptions
b. Workspace Configuration Check
const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; if (!workspaceFolder) return;- Checks if there's an open workspace
- Returns early if no workspace is found
c. ESLint Linter Initialization
const linter = new Linter({ configFilePath: path.join(workspaceFolder.uri.fsPath, '.eslintrc.json') });- Creates an ESLint linter instance
- Points to the project's
.eslintrc.jsonconfig file - Uses Node.js
pathmodule to handle file paths
d. Document Save Listener
vscode.workspace.onDidSaveTextDocument(document => { if (document.languageId !== 'javascript') return; // ... linting logic ... });- Triggers when any document is saved
- Only processes JavaScript files (languageId === 'javascript')
e. Linting Process
const text = document.getText(); const results = linter.verify(text, { env: { es6: true }, parserOptions: { ecmaVersion: 2022, sourceType: 'module' } }, { filename: document.fileName });- Gets current document text
- Runs ESLint verification with:
- ES6 environment
- 2022 ECMAScript version
- Module source type
- Current filename
f. Diagnostic Creation
const diagnostics: vscode.Diagnostic[] = results.map(result => { const start = document.positionAt(result.line - 1); const end = document.positionAt(result.line); return new vscode.Diagnostic( new vscode.Range(start, end), result.message, vscode.DiagnosticSeverity.Error ); });- Converts ESLint results to VSCode diagnostics
- Maps line numbers (1-based in ESLint → 0-based in VSCode)
- Creates error-level diagnostics for each ESLint issue
g. Diagnostic Display
vscode.languages.createDiagnosticCollection('eslint').set(document.uri, diagnostics);- Creates/updates a diagnostic collection named 'eslint'
- Shows errors in VSCode's Problems panel
h. Fix Command Registration
vscode.commands.registerCommand('eslint.fix', async () => { // ... auto-fix logic ... });- Creates a command
eslint.fixthat can be triggered via:- Command Palette (Ctrl+Shift+P)
- Keybinding
- Context menu
i. Auto-Fix Implementation
const fixed = linter.verifyAndFix(text, { /* config */ }); if (fixed.output) { await editor.edit(edit => { edit.replace( new vscode.Range(0, 0, text.length, 0), fixed.output ); }); }- Uses ESLint's
verifyAndFixto auto-correct issues - Replaces entire document text with fixed version
- Works for fixable ESLint rules (e.g., indentation, semicolons)
3. Dependencies (
package.json){ "dependencies": { "eslint": "^8.56.0" }, "devDependencies": { "@types/vscode": "^1.75.0", "typescript": "^5.3.0" } }- eslint: Core ESLint library
- @types/vscode: TypeScript definitions for VSCode API
- typescript: TypeScript compiler
4. Key Limitations (Improvement Opportunities)
-
Single File Support
Only lints active document on save - consider real-time linting -
Config Handling
The hardcoded config inverify()might override project ESLint rules -
Language Support
Only handles JavaScript - could add TypeScript/JSX support -
Diagnostic Precision
Only shows line-level errors - could use column positions for exact highlighting -
Workspace Trust
No handling of restricted workspace mode
5. How to Test
- Create a new extension project using
yo code - Add the code to
extension.ts - Run
npm install eslint --save - Create a test
.eslintrc.jsonin your workspace - Press F5 to debug the extension
Would you like me to explain any specific part in more detail?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.