Skip to content

Commit

Permalink
feat: shared logger and silent test logs (nuxt#3259)
Browse files Browse the repository at this point in the history
Co-authored-by: pooya parsa <pyapar@gmail.com>
  • Loading branch information
antfu and pi0 authored Feb 16, 2022
1 parent ad52b79 commit 467ab69
Show file tree
Hide file tree
Showing 32 changed files with 77 additions and 78 deletions.
1 change: 0 additions & 1 deletion packages/bridge/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
"@vue/composition-api": "^1.4.6",
"@vueuse/head": "^0.7.5",
"acorn": "^8.7.0",
"consola": "^2.15.3",
"cookie-es": "^0.5.0",
"defu": "^5.0.1",
"destr": "^1.1.0",
Expand Down
6 changes: 3 additions & 3 deletions packages/bridge/src/vite/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { resolve } from 'pathe'
import * as vite from 'vite'
import { createVuePlugin } from 'vite-plugin-vue2'
import PluginLegacy from '@vitejs/plugin-legacy'
import consola from 'consola'
import { logger } from '@nuxt/kit'
import { joinURL } from 'ufo'
import { devStyleSSRPlugin } from '../../../vite/src/plugins/dev-ssr-css'
import { jsxPlugin } from './plugins/jsx'
Expand Down Expand Up @@ -54,9 +54,9 @@ export async function buildClient (ctx: ViteBuildContext) {
// Production build
if (!ctx.nuxt.options.dev) {
const start = Date.now()
consola.info('Building client...')
logger.info('Building client...')
await vite.build(clientConfig)
consola.success(`Client built in ${Date.now() - start}ms`)
logger.success(`Client built in ${Date.now() - start}ms`)
return
}

Expand Down
7 changes: 3 additions & 4 deletions packages/bridge/src/vite/module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import consola from 'consola'
import { addPluginTemplate, defineNuxtModule } from '@nuxt/kit'
import { logger, addPluginTemplate, defineNuxtModule } from '@nuxt/kit'
import { version } from '../../package.json'
import { middlewareTemplate, storeTemplate } from './templates'
import type { ViteOptions } from './types'
Expand All @@ -15,9 +14,9 @@ export default defineNuxtModule<ViteOptions>({
nuxt.options.cli.badgeMessages.push(`⚡ Vite Mode Enabled (v${version})`)
// eslint-disable-next-line no-console
if (viteOptions.experimentWarning !== false && !nuxt.options.test) {
consola.log(
logger.log(
'🧪 Vite mode is experimental and some nuxt modules might be incompatible\n',
' If found a bug, please report via https://github.com/nuxt/vite/issues with a minimal reproduction.'
' If found a bug, please report via https://github.com/nuxt/framework/issues with a minimal reproduction.'
)
}

Expand Down
6 changes: 3 additions & 3 deletions packages/bridge/src/vite/server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { resolve } from 'pathe'
import * as vite from 'vite'
import { createVuePlugin } from 'vite-plugin-vue2'
import consola from 'consola'
import { logger } from '@nuxt/kit'
import fse from 'fs-extra'
import pDebounce from 'p-debounce'
import { bundleRequest } from '../../../vite/src/dev-bundler'
Expand Down Expand Up @@ -80,10 +80,10 @@ export async function buildServer (ctx: ViteBuildContext) {
// Production build
if (!ctx.nuxt.options.dev) {
const start = Date.now()
consola.info('Building server...')
logger.info('Building server...')
await vite.build(serverConfig)
await onBuild()
consola.success(`Server built in ${Date.now() - start}ms`)
logger.success(`Server built in ${Date.now() - start}ms`)
return
}

Expand Down
6 changes: 3 additions & 3 deletions packages/bridge/src/vite/vite.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { resolve } from 'pathe'
import * as vite from 'vite'
import consola from 'consola'
import { logger } from '@nuxt/kit'
import { withoutLeadingSlash } from 'ufo'
import { distDir } from '../dirs'
import { warmupViteServer } from '../../../vite/src/utils/warmup'
Expand Down Expand Up @@ -95,8 +95,8 @@ async function bundle (nuxt: Nuxt, builder: any) {
ctx.nuxt.hook('vite:serverCreated', (server: vite.ViteDevServer) => {
const start = Date.now()
warmupViteServer(server, ['/.nuxt/entry.mjs']).then(() => {
consola.info(`Vite warmed up in ${Date.now() - start}ms`)
}).catch(consola.error)
logger.info(`Vite warmed up in ${Date.now() - start}ms`)
}).catch(logger.error)
})
}

Expand Down
1 change: 1 addition & 0 deletions packages/kit/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export * from './plugin'
export * from './resolve'
export * from './server'
export * from './template'
export * from './logger'

// Internal Utils
// TODO
Expand Down
7 changes: 7 additions & 0 deletions packages/kit/src/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import consola from 'consola'

export const logger = consola

export function useLogger (scope?: string) {
return scope ? logger.withScope(scope) : logger
}
4 changes: 2 additions & 2 deletions packages/kit/src/module/container.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { parse, relative } from 'pathe'
import consola from 'consola'
import type { Nuxt, NuxtPluginTemplate, NuxtTemplate, ModuleContainer } from '@nuxt/schema'
import { logger } from '../logger'
import { chainFn } from '../internal/task'
import { addTemplate } from '../template'
import { addServerMiddleware } from '../server'
Expand Down Expand Up @@ -67,7 +67,7 @@ export function useModuleContainer (nuxt: Nuxt = useNuxt()): ModuleContainer {
const layout = nuxt.options.layouts[layoutName]

if (layout) {
consola.warn(`Duplicate layout registration, "${layoutName}" has been registered as "${layout}"`)
logger.warn(`Duplicate layout registration, "${layoutName}" has been registered as "${layout}"`)
}
nuxt.options.layouts[layoutName] = `./${filename}`
if (name === 'error') {
Expand Down
8 changes: 4 additions & 4 deletions packages/kit/src/module/define.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { promises as fsp } from 'fs'
import defu from 'defu'
import { applyDefaults } from 'untyped'
import consola from 'consola'
import { dirname } from 'pathe'
import type { Nuxt, NuxtTemplate, NuxtModule, ModuleOptions, ModuleDefinition } from '@nuxt/schema'
import { logger } from '../logger'
import { useNuxt, nuxtCtx } from '../context'
import { isNuxt2, checkNuxtCompatibility } from '../compatibility'
import { templateUtils, compileTemplate } from '../internal/template'
Expand All @@ -17,7 +17,7 @@ export function defineNuxtModule<OptionsT extends ModuleOptions> (definition: Mo
if (typeof definition === 'function') {
// @ts-ignore
definition = definition(useNuxt())
consola.warn('Module definition as function is deprecated and will be removed in the future versions', definition)
logger.warn('Module definition as function is deprecated and will be removed in the future versions', definition)
}

// Normalize definition and meta
Expand Down Expand Up @@ -57,11 +57,11 @@ export function defineNuxtModule<OptionsT extends ModuleOptions> (definition: Mo
nuxt.options._requiredModules[uniqueKey] = true
}

// Check compatibility contraints
// Check compatibility constraints
if (definition.meta.compatibility) {
const issues = await checkNuxtCompatibility(definition.meta.compatibility, nuxt)
if (issues.length) {
consola.warn(`Module \`${definition.meta.name}\` is disabled due to incompatibility issues:\n${issues.toString()}`)
logger.warn(`Module \`${definition.meta.name}\` is disabled due to incompatibility issues:\n${issues.toString()}`)
return
}
}
Expand Down
26 changes: 13 additions & 13 deletions packages/nitro/src/build.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { relative, resolve, join } from 'pathe'
import consola from 'consola'
import { logger } from '@nuxt/kit'
import * as rollup from 'rollup'
import fse from 'fs-extra'
import { genDynamicImport } from 'knitwork'
Expand All @@ -10,7 +10,7 @@ import { NitroContext } from './context'
import { scanMiddleware } from './server/middleware'

export async function prepare (nitroContext: NitroContext) {
consola.info(`Nitro preset is ${hl(nitroContext.preset)}`)
logger.info(`Nitro preset is ${hl(nitroContext.preset)}`)

await cleanupDir(nitroContext.output.dir)

Expand All @@ -24,12 +24,12 @@ export async function prepare (nitroContext: NitroContext) {
}

async function cleanupDir (dir: string) {
consola.info('Cleaning up', prettyPath(dir))
logger.info('Cleaning up', prettyPath(dir))
await fse.emptyDir(dir)
}

export async function generate (nitroContext: NitroContext) {
consola.start('Generating public...')
logger.start('Generating public...')

await nitroContext._internal.hooks.callHook('nitro:generate', nitroContext)

Expand All @@ -44,7 +44,7 @@ export async function generate (nitroContext: NitroContext) {
await fse.copy(clientDist, buildAssetsDir)
}

consola.success('Generated public ' + prettyPath(nitroContext.output.publicDir))
logger.success('Generated public ' + prettyPath(nitroContext.output.publicDir))
}

export async function build (nitroContext: NitroContext) {
Expand Down Expand Up @@ -96,13 +96,13 @@ async function _build (nitroContext: NitroContext) {
nitroContext.scannedMiddleware = await scanMiddleware(nitroContext._nuxt.serverDir)
await writeTypes(nitroContext)

consola.start('Building server...')
logger.start('Building server...')
const build = await rollup.rollup(nitroContext.rollupConfig).catch((error) => {
consola.error('Rollup error: ' + error.message)
logger.error('Rollup error: ' + error.message)
throw error
})

consola.start('Writing server bundle...')
logger.start('Writing server bundle...')
await build.write(nitroContext.rollupConfig.output)

const rewriteBuildPaths = (input: unknown, to: string) =>
Expand All @@ -120,18 +120,18 @@ async function _build (nitroContext: NitroContext) {
}
await writeFile(nitroConfigPath, JSON.stringify(buildInfo, null, 2))

consola.success('Server built')
logger.success('Server built')
await printFSTree(nitroContext.output.serverDir)
await nitroContext._internal.hooks.callHook('nitro:compiled', nitroContext)

// Show deploy and preview hints
const rOutDir = relative(process.cwd(), nitroContext.output.dir)
if (nitroContext.commands.preview) {
// consola.info(`You can preview this build using \`${rewriteBuildPaths(nitroContext.commands.preview, rOutDir)}\``)
consola.info('You can preview this build using `nuxi preview`')
logger.info('You can preview this build using `nuxi preview`')
}
if (nitroContext.commands.deploy) {
consola.info(`You can deploy this build using \`${rewriteBuildPaths(nitroContext.commands.deploy, rOutDir)}\``)
logger.info(`You can deploy this build using \`${rewriteBuildPaths(nitroContext.commands.deploy, rOutDir)}\``)
}

return {
Expand All @@ -157,12 +157,12 @@ function startRollupWatcher (nitroContext: NitroContext) {
// Finished building all bundles
case 'END':
nitroContext._internal.hooks.callHook('nitro:compiled', nitroContext)
consola.success('Nitro built', start ? `in ${Date.now() - start} ms` : '')
logger.success('Nitro built', start ? `in ${Date.now() - start} ms` : '')
return

// Encountered an error while bundling
case 'ERROR':
consola.error('Rollup error: ' + event.error)
logger.error('Rollup error: ' + event.error)
// consola.error(event.error)
}
})
Expand Down
4 changes: 2 additions & 2 deletions packages/nitro/src/presets/browser.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { existsSync, promises as fsp } from 'fs'
import { resolve } from 'pathe'
import consola from 'consola'
import { logger } from '@nuxt/kit'
import { joinURL } from 'ufo'
import { genString } from 'knitwork'
import { extendPreset, prettyPath } from '../utils'
Expand Down Expand Up @@ -77,7 +77,7 @@ if ('serviceWorker' in navigator) {
if (!existsSync(resolve(output.publicDir, '404.html'))) {
await fsp.writeFile(resolve(output.publicDir, '404.html'), html, 'utf8')
}
consola.info('Ready to deploy to static hosting:', prettyPath(output.publicDir as string))
logger.info('Ready to deploy to static hosting:', prettyPath(output.publicDir as string))
}
}
}
Expand Down
1 change: 0 additions & 1 deletion packages/nuxi/src/commands/build.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { resolve } from 'pathe'
import consola from 'consola'

import { writeTypes } from '../utils/prepare'
import { loadKit } from '../utils/kit'
import { clearDir } from '../utils/fs'
Expand Down
1 change: 0 additions & 1 deletion packages/nuxt3/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
"@vue/shared": "^3.2.31",
"@vueuse/head": "^0.7.5",
"chokidar": "^3.5.3",
"consola": "^2.15.3",
"cookie-es": "^0.5.0",
"defu": "^5.0.1",
"destr": "^1.1.0",
Expand Down
4 changes: 2 additions & 2 deletions packages/nuxt3/src/core/plugins/import-protection.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createRequire } from 'module'
import { createUnplugin } from 'unplugin'
import consola from 'consola'
import { logger } from '@nuxt/kit'
import { isAbsolute, relative, resolve } from 'pathe'
import type { Nuxt } from '@nuxt/schema'
import escapeRE from 'escape-string-regexp'
Expand Down Expand Up @@ -40,7 +40,7 @@ export const ImportProtectionPlugin = createUnplugin(function (options: ImportPr
if (cache[id].has(pattern)) { continue }

const relativeImporter = isAbsolute(importer) ? relative(options.rootDir, importer) : importer
consola.error(warning || 'Invalid import', `[importing \`${id}\` from \`${relativeImporter}\`]`)
logger.error(warning || 'Invalid import', `[importing \`${id}\` from \`${relativeImporter}\`]`)
cache[id].set(pattern, true)
matched = true
}
Expand Down
1 change: 1 addition & 0 deletions packages/schema/build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export default defineBuildConfig({
'webpack-bundle-analyzer',
'rollup-plugin-visualizer',
'vite',
'consola',
// Implicit
'@vue/compiler-core',
'@vue/shared'
Expand Down
6 changes: 3 additions & 3 deletions packages/schema/src/config/_common.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { join, resolve } from 'pathe'
import { isDevelopment } from 'std-env'
import { isDevelopment, isTest } from 'std-env'
import createRequire from 'create-require'
import { pascalCase } from 'scule'
import jiti from 'jiti'
import defu from 'defu'

export default {
/**
* Extend nested configurations from multiple local or remoted sources
* Extend nested configurations from multiple local or remote sources
*
* Value should be either a string or array of strings pointing to source directories or config path relative to current config.
*
Expand Down Expand Up @@ -738,5 +738,5 @@ export default {
*/
publicRuntimeConfig: {
$resolve: (val: Record<string, any> = {}, get) => ({ ...val, app: defu(val.app, get('app')) })
},
}
}
2 changes: 1 addition & 1 deletion packages/schema/src/types/nuxt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,4 @@ export interface NuxtApp {
}

type _TemplatePlugin = NuxtPlugin & NuxtTemplate
export interface NuxtPluginTemplate extends _TemplatePlugin {}
export interface NuxtPluginTemplate extends _TemplatePlugin { }
1 change: 1 addition & 0 deletions packages/test-utils/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export function createTestContext (options: Partial<TestOptions>): TestContext {
fixture: 'fixture',
configFile: 'nuxt.config',
setupTimeout: 60000,
logLevel: 1,
server: options.browser,
build: options.browser || options.server,
nuxtConfig: {},
Expand Down
2 changes: 2 additions & 0 deletions packages/test-utils/src/nuxt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ export async function loadFixture () {
configFile: ctx.options.configFile
})

kit.logger.level = ctx.options.logLevel

await fsp.mkdir(ctx.nuxt.options.buildDir, { recursive: true })
}

Expand Down
1 change: 1 addition & 0 deletions packages/test-utils/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export interface TestOptions {
waitFor: number
browser: boolean
runner: TestRunner
logLevel: number
browserOptions: {
type: 'chromium' | 'firefox' | 'webkit'
launch?: LaunchOptions
Expand Down
1 change: 0 additions & 1 deletion packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
"@vitejs/plugin-vue-jsx": "^1.3.7",
"autoprefixer": "^10.4.2",
"chokidar": "^3.5.3",
"consola": "^2.15.3",
"defu": "^5.0.1",
"esbuild": "^0.14.21",
"escape-string-regexp": "^5.0.0",
Expand Down
5 changes: 2 additions & 3 deletions packages/vite/src/client.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { resolve } from 'pathe'
import * as vite from 'vite'
import consola from 'consola'
import vuePlugin from '@vitejs/plugin-vue'
import viteJsxPlugin from '@vitejs/plugin-vue-jsx'
import type { Connect } from 'vite'

import { logger } from '@nuxt/kit'
import { joinURL } from 'ufo'
import { cacheDirPlugin } from './plugins/cache-dir'
import { analyzePlugin } from './plugins/analyze'
Expand Down Expand Up @@ -80,7 +79,7 @@ export async function buildClient (ctx: ViteBuildContext) {
const start = Date.now()
await vite.build(clientConfig)
await ctx.nuxt.callHook('build:resources', wpfs)
consola.info(`Client built in ${Date.now() - start}ms`)
logger.info(`Client built in ${Date.now() - start}ms`)
}

await writeManifest(ctx)
Expand Down
Loading

0 comments on commit 467ab69

Please sign in to comment.