閱讀有關創建提供命令的 VS Code 擴展的官方檔案(參見例如:擴展條目檔案、VS Code Api - 命令等),給出的示例使用此模式:
- 擴展在呼叫它應該定義的命令時被激活
- 它在那里定義命令的代碼(在其
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()擴展中的所有函式后正在檢查命令的處理程式; - 在上面的函式之前的評論,它說,該擴展被激活時,執行命令的第一次,但對DOC的
onCommand激活事件實際上指出擴展呼叫的任何時間的呼叫命令; 該宣告也與我所理解的模式相反,即在每次呼叫時“以原子方式”激活擴展/注冊命令; - 我假設
disposable這里取消注冊命令,以便處理程式在每次呼叫時都與命令新關聯(檔案對此不清楚); - 這種整體模式(在呼叫命令時激活擴展,立即注冊命令,然后停用擴展并取消注冊命令)是為了改善記憶體消耗(例如,僅在定義命令時呼叫擴展,而不是在開始時呼叫擴展) VS Code)或其他原因?
感謝您的澄清,如果我一開始就沒有正確理解該模式,我深表歉意。
uj5u.com熱心網友回復:
您是否閱讀過該package.json檔案,其中說明應何時激活擴展名:activationEvents
在啟動時,VSC 會在命令表中為 中定義的每個擴展命令放置一個 load_extension 函式句柄package.json。
當您第一次呼叫命令時,將呼叫 load_extension 函式并加載擴展,并使用實際的命令函式句柄更新命令表。并且再次呼叫命令函式,現在具有正確的函式。
這是懶惰的擴展激活,如果您不使用擴展此會話不需要一些作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/386176.html
