Skip to content

Commit

Permalink
fix: use Vite's native logger to log and clean screen before log (#209)
Browse files Browse the repository at this point in the history
  • Loading branch information
fi3ework committed Jan 27, 2023
1 parent 9ceacd6 commit 8dd4915
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 55 deletions.
8 changes: 1 addition & 7 deletions packages/vite-plugin-checker/src/Checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import { isInVitestEntryThread, isMainThread } from './utils.js'

import { createScript, Script } from './worker.js'

// still an only issue https://github.com/microsoft/TypeScript/issues/29808#issuecomment-829750974
import type {} from 'vite'
import type {
CreateDiagnostic,
BuildInCheckers,
Expand All @@ -25,11 +23,7 @@ export interface CheckerMeta<T extends BuildInCheckerNames> {
}

export abstract class Checker<T extends BuildInCheckerNames> implements CheckerMeta<T> {
public static logger: ((...args: any[]) => void)[] = [
(...args: any[]) => {
console.log(args[0].payload)
},
]
public static logger: ((...v: string[]) => unknown)[] = []

public static log(...args: any[]) {
this.logger.forEach((fn) => fn(...args))
Expand Down
73 changes: 37 additions & 36 deletions packages/vite-plugin-checker/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ import {
BuildInCheckerNames,
ClientDiagnosticPayload,
ClientReconnectPayload,
OverlayErrorAction,
Action,
PluginConfig,
ServeAndBuildChecker,
SharedConfig,
UserPluginConfig,
} from './types.js'

import type { ConfigEnv, Plugin, ResolvedConfig } from 'vite'
import type { ConfigEnv, Plugin, Logger } from 'vite'
const sharedConfigKeys: (keyof SharedConfig)[] = ['enableBuild', 'overlay']
const buildInCheckerKeys: BuildInCheckerNames[] = [
'typescript',
Expand Down Expand Up @@ -61,12 +61,11 @@ export function checker(userConfig: UserPluginConfig): Plugin {
let initialized = false
let initializeCounter = 0
let checkers: ServeAndBuildChecker[] = []
let isProduction = true
let skipRuntime = false
let devBase = '/'

let viteMode: ConfigEnv['command'] | undefined
let resolvedConfig: ResolvedConfig | undefined
let buildWatch = false
let logger: Logger | null = null

return {
name: 'vite-plugin-checker',
Expand Down Expand Up @@ -98,10 +97,10 @@ export function checker(userConfig: UserPluginConfig): Plugin {
})
},
configResolved(config) {
resolvedConfig = config
logger = config.logger
devBase = config.base
isProduction = config.isProduction
skipRuntime ||= isProduction || config.command === 'build'
skipRuntime ||= config.isProduction || config.command === 'build'
buildWatch = !!config.build.watch
},
buildEnd() {
if (initialized) return
Expand Down Expand Up @@ -139,7 +138,7 @@ export function checker(userConfig: UserPluginConfig): Plugin {
{
tag: 'script',
attrs: { type: 'module' },
children: composePreambleCode(resolvedConfig!.base, overlayConfig),
children: composePreambleCode(devBase, overlayConfig),
},
]
},
Expand All @@ -162,7 +161,7 @@ export function checker(userConfig: UserPluginConfig): Plugin {
)
const exitCode = exitCodes.find((code) => code !== 0) ?? 0
// do not exit the process if run `vite build --watch`
if (exitCode !== 0 && !resolvedConfig?.build.watch) {
if (exitCode !== 0 && !buildWatch) {
process.exit(exitCode)
}
})()
Expand All @@ -176,43 +175,45 @@ export function checker(userConfig: UserPluginConfig): Plugin {
checkers.forEach((checker, index) => {
const { worker, configureServer: workerConfigureServer } = checker.serve
workerConfigureServer({ root: server.config.root })
worker.on('message', (action: OverlayErrorAction) => {
worker.on('message', (action: Action) => {
if (action.type === ACTION_TYPES.overlayError) {
latestOverlayErrors[index] = action.payload as ClientDiagnosticPayload
if (action.payload) {
server.ws.send('vite-plugin-checker', action.payload)
}
} else if (action.type === ACTION_TYPES.console) {
Checker.log(action)
if (Checker.logger.length) {
// for test injection and customize logger in the future
Checker.log(action)
} else {
logger!.error(action.payload)
}
}
})
})

return () => {
if (server.ws.on) {
server.ws.on('vite-plugin-checker', (data) => {
// NOTE: sync modification with packages /packages/runtime/src/ws.js
if (data.event === 'runtime-loaded') {
server.ws.send('vite-plugin-checker', {
event: WS_CHECKER_RECONNECT_EVENT,
data: latestOverlayErrors.filter(Boolean),
})
}
})
} else {
setTimeout(() => {
console.warn(
chalk.yellow(
"[vite-plugin-checker]: `server.ws.on` is introduced to Vite in 2.6.8, see [PR](https://github.com/vitejs/vite/pull/5273) and [changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md#268-2021-10-18). \nvite-plugin-checker relies on `server.ws.on` to bring diagnostics back after a full reload and it' not available for you now due to the old version of Vite. You can upgrade Vite to latest version to eliminate this warning."
)
)
// make a delay to avoid flush by Vite's console
}, 5000)
}

server.middlewares.use((req, res, next) => {
next()
if (server.ws.on) {
server.watcher.on('change', (file) => {
logger!.clearScreen('error')
})
server.ws.on('vite-plugin-checker', (data) => {
// NOTE: sync modification with packages /packages/runtime/src/ws.js
if (data.event === 'runtime-loaded') {
server.ws.send('vite-plugin-checker', {
event: WS_CHECKER_RECONNECT_EVENT,
data: latestOverlayErrors.filter(Boolean),
})
}
})
} else {
setTimeout(() => {
logger!.warn(
chalk.yellow(
'[vite-plugin-checker]: `server.ws.on` is introduced to Vite in 2.6.8, see [PR](https://github.com/vitejs/vite/pull/5273) and [changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md#268-2021-10-18). \nvite-plugin-checker relies on `server.ws.on` to send overlay message to client. Support for Vite < 2.6.8 will be removed in the next major version release.'
)
)
// make a delay to avoid flush by Vite's console
}, 5000)
}
},
}
Expand Down
34 changes: 22 additions & 12 deletions packages/vite-plugin-checker/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,12 +187,12 @@ export enum ACTION_TYPES {
unref = 'unref',
}

interface Action {
interface AbstractAction {
type: string
payload: unknown
}

export interface OverlayErrorAction extends Action {
export interface OverlayErrorAction extends AbstractAction {
type: ACTION_TYPES.overlayError
/**
* send `ClientPayload` to raise error overlay
Expand All @@ -201,29 +201,39 @@ export interface OverlayErrorAction extends Action {
payload: ClientPayload
}

interface ConfigActionPayload {
enableOverlay: boolean
enableTerminal: boolean
env: ConfigEnv
}

export interface ConfigAction extends Action {
export interface ConfigAction extends AbstractAction {
type: ACTION_TYPES.config
payload: ConfigActionPayload
}

export interface ConfigureServerAction extends Action {
export interface ConfigureServerAction extends AbstractAction {
type: ACTION_TYPES.configureServer
payload: {
root: string
}
}

export interface UnrefAction extends Action {
export interface ConsoleAction extends AbstractAction {
type: ACTION_TYPES.console
payload: string
}

export interface UnrefAction extends AbstractAction {
type: ACTION_TYPES.unref
}

export type Actions = OverlayErrorAction | ConfigAction | ConfigureServerAction | UnrefAction
interface ConfigActionPayload {
enableOverlay: boolean
enableTerminal: boolean
env: ConfigEnv
}

export type Action =
| ConfigAction
| ConfigureServerAction
| ConsoleAction
| OverlayErrorAction
| UnrefAction

/* ----------------------------- internal types ----------------------------- */

Expand Down

0 comments on commit 8dd4915

Please sign in to comment.