How to create/write to a output channel only once?

Viewed 149

I'm trying to learn how to create a vscode extension

theres a function that im printing some text to console, however each time the function is called, it creates a new output channel:

const channel = vscode.window.createOutputChannel("debug");
channel.show();
console.log("test");

how i could avoid it? I mean, create the channel only once.

1 Answers

Like with any other part you want to share in a JS/TS project, you have to export it. In my extension.ts I created the output channel in the activate function and provide an exported print function to access it:

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);
    }
};

Now you can import printChannelOutput in any of your extension files and call it with the text you want to print.

Related