【发布时间】:2023-03-02 21:14:01
【问题描述】:
阅读官方文档以创建贡献命令的 VS Code 扩展(参见例如:Extension Entry File、VS Code Api - commands 等)给出的示例使用了这种模式:
- 扩展在调用它应该定义的命令时被激活
- 它在那里定义了命令的代码(在其
activate()函数中)
为了更清楚起见,我在此处提供activate() 函数的示例代码:
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "helloworld-sample" is now active!');
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
let disposable = vscode.commands.registerCommand('helloworld.helloWorld', () => {
// The code you place here will be executed every time your command is executed
// Display a message box to the user
vscode.window.showInformationMessage('Hello World!');
});
context.subscriptions.push(disposable);
}
现在,除了这不是我从仅仅“直观”的角度为扩展贡献命令所期望的模式(可能是“定义新命令的扩展应该在VS Code 的开始,以便它的命令从那里可用等”),我有几个问题,显然只是要求澄清,因为事情是这样工作的,甚至被呈现为“官方”:
- 如果扩展程序在其调用时定义了命令代码,如何运行(此处为“hello world”消息)?我假设 VS Code 在处理完所有来自扩展的
activate()函数后会检查命令的处理程序; - 在上述函数之前的注释中,声明扩展在第一次执行命令时被激活,但
onCommand激活事件的文档实际上声明扩展在任何时候调用该命令;该声明也与我理解的模式相反,即在每次调用时“原子地”激活扩展/注册命令; - 我假设这里的
disposable取消注册命令,以便处理程序在每次调用时与命令新关联(文档对此并不清楚); - 是这种整体模式(在调用命令时激活扩展,立即注册命令,然后停用扩展并取消注册命令)旨在改善内存消耗(例如,仅在定义命令时调用扩展而不是在 VS Code 的开头)或其他原因?
感谢您的澄清,如果我一开始没有正确理解该模式,我们深表歉意。
【问题讨论】:
标签: visual-studio-code vscode-extensions