如何仅创建/写入输出通道一次?

Ces*_*sar 2 visual-studio-code vscode-extensions

我正在尝试学习如何创建 vscode 扩展

有一个函数可以将一些文本打印到控制台,但是每次调用该函数时,它都会创建一个新的输出通道:

const channel = vscode.window.createOutputChannel("debug");
channel.show();
console.log("test");
Run Code Online (Sandbox Code Playgroud)

我怎样才能避免它?我的意思是,只创建一次频道。

Mik*_*hke 8

与您想要在 JS/TS 项目中共享的任何其他部分一样,您必须将其导出。在我的 extension.ts 中,我在函数中创建了输出通道activate,并提供了一个导出的打印函数来访问它:

let outputChannel: OutputChannel;

export const activate = (context: ExtensionContext): void => {
    outputChannel = window.createOutputChannel("My Extension");
...
}

/**
 * Prints the given content on the output channel.
 *
 * @param content The content to be printed.
 * @param reveal Whether the output channel should be revealed.
 */
export const printChannelOutput = (content: string, reveal = false): void => {
    outputChannel.appendLine(content);
    if (reveal) {
        outputChannel.show(true);
    }
};
Run Code Online (Sandbox Code Playgroud)

现在,您可以导入printChannelOutput任何扩展文件并使用要打印的文本调用它。