From 0092e0c1c3fa564b52662e208193f98cfd936aa9 Mon Sep 17 00:00:00 2001 From: await-ovo <13152410380@163.com> Date: Fri, 18 Nov 2022 23:02:44 +0800 Subject: [PATCH] fix: use postMessage instead of console in worker thread --- src/index.ts | 7 +++++++ src/log.ts | 40 ++++++++++++++++++++++++++++------------ 2 files changed, 35 insertions(+), 12 deletions(-) diff --git a/src/index.ts b/src/index.ts index 9552ebbc..0f6775a1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -180,6 +180,13 @@ export async function build(_options: Options) { reject(new Error('error occured in dts build')) } else if (data === 'success') { resolve() + } else { + const { type, text } = data + if (type === 'log') { + console.log(text) + } else if (type === 'error') { + console.error(text) + } } }) }) diff --git a/src/log.ts b/src/log.ts index f782cdce..0c1cd498 100644 --- a/src/log.ts +++ b/src/log.ts @@ -1,3 +1,5 @@ +import util from 'util' +import { parentPort, isMainThread } from 'worker_threads' import * as colors from 'colorette' type LOG_TYPE = 'info' | 'success' | 'error' | 'warn' @@ -9,10 +11,10 @@ export const colorize = (type: LOG_TYPE, data: any, onlyImportant = false) => { type === 'info' ? 'blue' : type === 'error' - ? 'red' - : type === 'warn' - ? 'yellow' - : 'green' + ? 'red' + : type === 'warn' + ? 'yellow' + : 'green' return colors[color](data) } @@ -68,20 +70,34 @@ export const createLogger = (name?: string) => { type: 'info' | 'success' | 'error' | 'warn', ...data: unknown[] ) { + const args = [ + makeLabel(name, label, type), + ...data.map((item) => colorize(type, item, true)), + ] switch (type) { case 'error': { - return console.error( - makeLabel(name, label, type), - ...data.map((item) => colorize(type, item, true)) - ) + if (!isMainThread) { + parentPort?.postMessage({ + type: 'error', + text: util.format(...args), + }) + return + } + + return console.error(...args) } default: if (silent) return - console.log( - makeLabel(name, label, type), - ...data.map((item) => colorize(type, item, true)) - ) + if (!isMainThread) { + parentPort?.postMessage({ + type: 'log', + text: util.format(...args), + }) + return + } + + console.log(...args) } }, }