This is for developers of VSCode extensions.
If you find the activate
method of your extension.ts
file feeling a little cluttered, perhaps this can help.
The idea is that instead of manually registering each command of your extension, just make a new class file for each command.
npm i @revrenlove/easy-vscode-commands
Enable experimentalDecorators
.
tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true
}
}
package.json
{
"contributes": {
"commands": [
{
"command": "your-org.howdyEarth",
"title": "Howdy, Earth!"
}
]
}
}
src/howdy-earth-command.ts
import * as vscode from 'vscode';
import { CommandBase, commandId } from '@revrenlove/easy-vscode-commands';
@commandId('your-org.howdyEarth')
export class HowdyEarthCommand extends CommandBase {
public execute(): void {
vscode.window.showInformationMessage('Howdy, Earth!');
}
}
src/extension.ts
import * as vscode from 'vscode';
import { registerCommands } from '@revrenlove/easy-vscode-commands';
import { HowdyEarthCommand } from './howdy-earth-command';
export function activate(context: vscode.ExtensionContext) {
registerCommands(context, [HowdyEarthCommand]);
}
export function deactivate() { }
src/fancy-command.ts
import * as vscode from 'vscode';
import { CommandBase, commandId } from '@revrenlove/easy-vscode-commands';
import { HowdyEarthCommand } from './howdy-earth-command';
@commandId('your-org.fancy')
export class FancyCommand extends CommandBase {
// `async`/`await` is supported
public async execute(): Promise<void> {
// Access `vscode.ExtensionContext` instance with `this.context`
const extensionId = this.context.extension.id;
await vscode.window.showInformationMessage(`Extension Id: ${extensionId}`);
// Static `commandId` property (comes from the `commandId` decorator)
vscode.commands.executeCommand(HowdyEarthCommand.commandId);
}
}
The second parameter of the registerCommands
function accepts an array of EasyVsCodeCommand
types - any class definition extending CommandBase
qualifies.
What I like to do is have all my commands in a commands
folder with an index.ts
that exports an array of all the commands.
For example:
commands/index.ts
import { HelloWorldCommand } from './hello-world-command.ts';
import { HelloMoonCommand } from './hello-moon-command.ts';
const commands: EasyVsCodeCommand[] = [
HelloWorldCommand,
HelloMoonCommand
];
export { commands };
And then in the extension.ts
:
import * as vscode from 'vscode';
import { registerCommands } from '@revrenlove/easy-vscode-commands';
import { commands } from './commands';
export function activate(context: vscode.ExtensionContext) {
registerCommands(context, commands);
}
export function deactivate() { }
-
Register the
vscode.ExtensionContext
instance in your container. -
Inject that into your command.
-
Call
super
and pass in thevscode.ExtensionContext
instance.