refactor(nuxt): use consola with nuxt tag instead of console (#30408)

This commit is contained in:
Julien Huang 2024-12-30 00:25:29 +01:00 committed by GitHub
parent 2b49c5b936
commit ca6e31c5d6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 37 additions and 21 deletions

View File

@ -1,9 +1,10 @@
import { existsSync, statSync, writeFileSync } from 'node:fs' import { existsSync, statSync, writeFileSync } from 'node:fs'
import { isAbsolute, join, normalize, relative, resolve } from 'pathe' import { isAbsolute, join, normalize, relative, resolve } from 'pathe'
import { addBuildPlugin, addPluginTemplate, addTemplate, addTypeTemplate, addVitePlugin, defineNuxtModule, findPath, logger, resolveAlias, resolvePath, updateTemplates } from '@nuxt/kit' import { addBuildPlugin, addPluginTemplate, addTemplate, addTypeTemplate, addVitePlugin, defineNuxtModule, findPath, resolveAlias, resolvePath, updateTemplates } from '@nuxt/kit'
import type { Component, ComponentsDir, ComponentsOptions } from 'nuxt/schema' import type { Component, ComponentsDir, ComponentsOptions } from 'nuxt/schema'
import { distDir } from '../dirs' import { distDir } from '../dirs'
import { logger } from '../utils'
import { componentNamesTemplate, componentsIslandsTemplate, componentsMetadataTemplate, componentsPluginTemplate, componentsTypeTemplate } from './templates' import { componentNamesTemplate, componentsIslandsTemplate, componentsMetadataTemplate, componentsPluginTemplate, componentsTypeTemplate } from './templates'
import { scanComponents } from './scan' import { scanComponents } from './scan'

View File

@ -5,9 +5,10 @@ import { pascalCase } from 'scule'
import { relative } from 'pathe' import { relative } from 'pathe'
import type { Component, ComponentsOptions } from 'nuxt/schema' import type { Component, ComponentsOptions } from 'nuxt/schema'
import { logger, tryUseNuxt } from '@nuxt/kit' import { tryUseNuxt } from '@nuxt/kit'
import { QUOTE_RE, SX_RE, isVue } from '../../core/utils' import { QUOTE_RE, SX_RE, isVue } from '../../core/utils'
import { installNuxtModule } from '../../core/features' import { installNuxtModule } from '../../core/features'
import { logger } from '../../utils'
interface LoaderOptions { interface LoaderOptions {
getComponents (): Component[] getComponents (): Component[]

View File

@ -2,11 +2,12 @@ import { readdir } from 'node:fs/promises'
import { basename, dirname, extname, join, relative } from 'pathe' import { basename, dirname, extname, join, relative } from 'pathe'
import { globby } from 'globby' import { globby } from 'globby'
import { kebabCase, pascalCase, splitByCase } from 'scule' import { kebabCase, pascalCase, splitByCase } from 'scule'
import { isIgnored, logger, useNuxt } from '@nuxt/kit' import { isIgnored, useNuxt } from '@nuxt/kit'
import { withTrailingSlash } from 'ufo' import { withTrailingSlash } from 'ufo'
import type { Component, ComponentsDir } from 'nuxt/schema' import type { Component, ComponentsDir } from 'nuxt/schema'
import { QUOTE_RE, resolveComponentNameSegments } from '../core/utils' import { QUOTE_RE, resolveComponentNameSegments } from '../core/utils'
import { logger } from '../utils'
const ISLAND_RE = /\.island(?:\.global)?$/ const ISLAND_RE = /\.island(?:\.global)?$/
const GLOBAL_RE = /\.global(?:\.island)?$/ const GLOBAL_RE = /\.global(?:\.island)?$/

View File

@ -1,11 +1,12 @@
import { promises as fsp, mkdirSync, writeFileSync } from 'node:fs' import { promises as fsp, mkdirSync, writeFileSync } from 'node:fs'
import { dirname, join, relative, resolve } from 'pathe' import { dirname, join, relative, resolve } from 'pathe'
import { defu } from 'defu' import { defu } from 'defu'
import { findPath, logger, normalizePlugin, normalizeTemplate, resolveAlias, resolveFiles, resolvePath } from '@nuxt/kit' import { findPath, normalizePlugin, normalizeTemplate, resolveAlias, resolveFiles, resolvePath } from '@nuxt/kit'
import type { Nuxt, NuxtApp, NuxtPlugin, NuxtTemplate, ResolvedNuxtTemplate } from 'nuxt/schema' import type { Nuxt, NuxtApp, NuxtPlugin, NuxtTemplate, ResolvedNuxtTemplate } from 'nuxt/schema'
import type { PluginMeta } from 'nuxt/app' import type { PluginMeta } from 'nuxt/app'
import { logger } from '../utils'
import * as defaultTemplates from './templates' import * as defaultTemplates from './templates'
import { getNameFromPath, hasSuffix, uniqueBy } from './utils' import { getNameFromPath, hasSuffix, uniqueBy } from './utils'
import { extractMetadata, orderMap } from './plugins/plugin-metadata' import { extractMetadata, orderMap } from './plugins/plugin-metadata'

View File

@ -1,11 +1,12 @@
import type { EventType } from '@parcel/watcher' import type { EventType } from '@parcel/watcher'
import type { FSWatcher } from 'chokidar' import type { FSWatcher } from 'chokidar'
import { watch as chokidarWatch } from 'chokidar' import { watch as chokidarWatch } from 'chokidar'
import { importModule, isIgnored, logger, tryResolveModule, useNuxt } from '@nuxt/kit' import { importModule, isIgnored, tryResolveModule, useNuxt } from '@nuxt/kit'
import { debounce } from 'perfect-debounce' import { debounce } from 'perfect-debounce'
import { normalize, relative, resolve } from 'pathe' import { normalize, relative, resolve } from 'pathe'
import type { Nuxt, NuxtBuilder } from 'nuxt/schema' import type { Nuxt, NuxtBuilder } from 'nuxt/schema'
import { logger } from '../utils'
import { generateApp as _generateApp, createApp } from './app' import { generateApp as _generateApp, createApp } from './app'
import { checkForExternalConfigurationFiles } from './external-config-files' import { checkForExternalConfigurationFiles } from './external-config-files'
import { cleanupCaches, getVueHash } from './cache' import { cleanupCaches, getVueHash } from './cache'

View File

@ -1,5 +1,6 @@
import { findPath, logger } from '@nuxt/kit' import { findPath } from '@nuxt/kit'
import { basename } from 'pathe' import { basename } from 'pathe'
import { logger } from '../utils'
/** /**
* Check for those external configuration files that are not compatible with Nuxt, * Check for those external configuration files that are not compatible with Nuxt,

View File

@ -1,7 +1,8 @@
import { addDependency } from 'nypm' import { addDependency } from 'nypm'
import { resolvePackageJSON } from 'pkg-types' import { resolvePackageJSON } from 'pkg-types'
import { logger, useNuxt } from '@nuxt/kit' import { useNuxt } from '@nuxt/kit'
import { isCI, provider } from 'std-env' import { isCI, provider } from 'std-env'
import { logger } from '../utils'
const isStackblitz = provider === 'stackblitz' const isStackblitz = provider === 'stackblitz'

View File

@ -4,7 +4,7 @@ import { join, normalize, relative, resolve } from 'pathe'
import { createDebugger, createHooks } from 'hookable' import { createDebugger, createHooks } from 'hookable'
import ignore from 'ignore' import ignore from 'ignore'
import type { LoadNuxtOptions } from '@nuxt/kit' import type { LoadNuxtOptions } from '@nuxt/kit'
import { addBuildPlugin, addComponent, addPlugin, addPluginTemplate, addRouteMiddleware, addServerPlugin, addTypeTemplate, addVitePlugin, addWebpackPlugin, installModule, loadNuxtConfig, logger, nuxtCtx, resolveAlias, resolveFiles, resolveIgnorePatterns, resolvePath, tryResolveModule, useNitro } from '@nuxt/kit' import { addBuildPlugin, addComponent, addPlugin, addPluginTemplate, addRouteMiddleware, addServerPlugin, addTypeTemplate, addVitePlugin, addWebpackPlugin, installModule, loadNuxtConfig, nuxtCtx, resolveAlias, resolveFiles, resolveIgnorePatterns, resolvePath, tryResolveModule, useNitro } from '@nuxt/kit'
import type { Nuxt, NuxtHooks, NuxtModule, NuxtOptions } from 'nuxt/schema' import type { Nuxt, NuxtHooks, NuxtModule, NuxtOptions } from 'nuxt/schema'
import type { PackageJson } from 'pkg-types' import type { PackageJson } from 'pkg-types'
import { readPackageJSON } from 'pkg-types' import { readPackageJSON } from 'pkg-types'
@ -31,6 +31,7 @@ import importsModule from '../imports/module'
import { distDir, pkgDir } from '../dirs' import { distDir, pkgDir } from '../dirs'
import { version } from '../../package.json' import { version } from '../../package.json'
import { scriptsStubsPreset } from '../imports/presets' import { scriptsStubsPreset } from '../imports/presets'
import { logger } from '../utils'
import { resolveTypePath } from './utils/types' import { resolveTypePath } from './utils/types'
import { createImportProtectionPatterns } from './plugins/import-protection' import { createImportProtectionPatterns } from './plugins/import-protection'
import { UnctxTransformPlugin } from './plugins/unctx' import { UnctxTransformPlugin } from './plugins/unctx'

View File

@ -6,10 +6,10 @@ import type { Nuxt } from '@nuxt/schema'
import { createUnplugin } from 'unplugin' import { createUnplugin } from 'unplugin'
import MagicString from 'magic-string' import MagicString from 'magic-string'
import { normalize } from 'pathe' import { normalize } from 'pathe'
import { logger } from '@nuxt/kit'
import type { ObjectPlugin, PluginMeta } from 'nuxt/app' import type { ObjectPlugin, PluginMeta } from 'nuxt/app'
import { parseAndWalk, withLocations } from '../../core/utils/parse' import { parseAndWalk, withLocations } from '../../core/utils/parse'
import { logger } from '../../utils'
const internalOrderMap = { const internalOrderMap = {
// -50: pre-all (nuxt) // -50: pre-all (nuxt)

View File

@ -1,10 +1,11 @@
import { parseNodeModulePath, resolvePath } from 'mlly' import { parseNodeModulePath, resolvePath } from 'mlly'
import { isAbsolute, normalize } from 'pathe' import { isAbsolute, normalize } from 'pathe'
import type { Plugin } from 'vite' import type { Plugin } from 'vite'
import { logger, resolveAlias } from '@nuxt/kit' import { resolveAlias } from '@nuxt/kit'
import type { Nuxt } from '@nuxt/schema' import type { Nuxt } from '@nuxt/schema'
import { pkgDir } from '../../dirs' import { pkgDir } from '../../dirs'
import { logger } from '../../utils'
export function resolveDeepImportsPlugin (nuxt: Nuxt): Plugin { export function resolveDeepImportsPlugin (nuxt: Nuxt): Plugin {
const exclude: string[] = ['virtual:', '\0virtual:', '/__skip_vite', '@vitest/'] const exclude: string[] = ['virtual:', '\0virtual:', '/__skip_vite', '@vitest/']

View File

@ -5,7 +5,7 @@ import { resolve } from 'pathe'
import { watch } from 'chokidar' import { watch } from 'chokidar'
import { defu } from 'defu' import { defu } from 'defu'
import { debounce } from 'perfect-debounce' import { debounce } from 'perfect-debounce'
import { createResolver, defineNuxtModule, importModule, logger, tryResolveModule } from '@nuxt/kit' import { createResolver, defineNuxtModule, importModule, tryResolveModule } from '@nuxt/kit'
import { import {
generateTypes, generateTypes,
resolveSchema as resolveUntypedSchema, resolveSchema as resolveUntypedSchema,
@ -13,6 +13,7 @@ import {
import type { Schema, SchemaDefinition } from 'untyped' import type { Schema, SchemaDefinition } from 'untyped'
import untypedPlugin from 'untyped/babel-plugin' import untypedPlugin from 'untyped/babel-plugin'
import { createJiti } from 'jiti' import { createJiti } from 'jiti'
import { logger } from '../utils'
export default defineNuxtModule({ export default defineNuxtModule({
meta: { meta: {

View File

@ -1,5 +1,5 @@
import { existsSync } from 'node:fs' import { existsSync } from 'node:fs'
import { addBuildPlugin, addTemplate, addTypeTemplate, defineNuxtModule, isIgnored, logger, resolveAlias, tryResolveModule, updateTemplates, useNuxt } from '@nuxt/kit' import { addBuildPlugin, addTemplate, addTypeTemplate, defineNuxtModule, isIgnored, resolveAlias, tryResolveModule, updateTemplates, useNuxt } from '@nuxt/kit'
import { isAbsolute, join, normalize, relative, resolve } from 'pathe' import { isAbsolute, join, normalize, relative, resolve } from 'pathe'
import type { Import, Unimport } from 'unimport' import type { Import, Unimport } from 'unimport'
import { createUnimport, scanDirExports, toExports } from 'unimport' import { createUnimport, scanDirExports, toExports } from 'unimport'
@ -7,7 +7,7 @@ import type { ImportPresetWithDeprecation, ImportsOptions, ResolvedNuxtTemplate
import escapeRE from 'escape-string-regexp' import escapeRE from 'escape-string-regexp'
import { lookupNodeModuleSubpath, parseNodeModulePath } from 'mlly' import { lookupNodeModuleSubpath, parseNodeModulePath } from 'mlly'
import { isDirectory } from '../utils' import { isDirectory, logger } from '../utils'
import { TransformPlugin } from './transform' import { TransformPlugin } from './transform'
import { defaultPresets } from './presets' import { defaultPresets } from './presets'

View File

@ -1,6 +1,6 @@
import { existsSync, readdirSync } from 'node:fs' import { existsSync, readdirSync } from 'node:fs'
import { mkdir, readFile } from 'node:fs/promises' import { mkdir, readFile } from 'node:fs/promises'
import { addBuildPlugin, addComponent, addPlugin, addTemplate, addTypeTemplate, defineNuxtModule, findPath, logger, resolvePath, updateTemplates, useNitro } from '@nuxt/kit' import { addBuildPlugin, addComponent, addPlugin, addTemplate, addTypeTemplate, defineNuxtModule, findPath, resolvePath, updateTemplates, useNitro } from '@nuxt/kit'
import { dirname, join, relative, resolve } from 'pathe' import { dirname, join, relative, resolve } from 'pathe'
import { genImport, genObjectFromRawEntries, genString } from 'knitwork' import { genImport, genObjectFromRawEntries, genString } from 'knitwork'
import { joinURL } from 'ufo' import { joinURL } from 'ufo'
@ -14,6 +14,7 @@ import type { NitroRouteConfig } from 'nitro/types'
import { defu } from 'defu' import { defu } from 'defu'
import { distDir } from '../dirs' import { distDir } from '../dirs'
import { resolveTypePath } from '../core/utils/types' import { resolveTypePath } from '../core/utils/types'
import { logger } from '../utils'
import { normalizeRoutes, resolvePagesRoutes, resolveRoutePaths } from './utils' import { normalizeRoutes, resolvePagesRoutes, resolveRoutePaths } from './utils'
import { extractRouteRules, getMappedPages } from './route-rules' import { extractRouteRules, getMappedPages } from './route-rules'
import { PageMetaPlugin } from './plugins/page-meta' import { PageMetaPlugin } from './plugins/page-meta'

View File

@ -5,7 +5,6 @@ import type { StaticImport } from 'mlly'
import { findExports, findStaticImports, parseStaticImport } from 'mlly' import { findExports, findStaticImports, parseStaticImport } from 'mlly'
import MagicString from 'magic-string' import MagicString from 'magic-string'
import { isAbsolute } from 'pathe' import { isAbsolute } from 'pathe'
import { logger } from '@nuxt/kit'
import { import {
ScopeTracker, ScopeTracker,
@ -16,6 +15,7 @@ import {
walk, walk,
withLocations, withLocations,
} from '../../core/utils/parse' } from '../../core/utils/parse'
import { logger } from '../../utils'
interface PageMetaPluginOptions { interface PageMetaPluginOptions {
dev?: boolean dev?: boolean
@ -184,7 +184,7 @@ export const PageMetaPlugin = (options: PageMetaPluginOptions = {}) => createUnp
walk(decl.init, { walk(decl.init, {
enter: (node, parent) => { enter: (node, parent) => {
if (node.type === 'AwaitExpression') { if (node.type === 'AwaitExpression') {
logger.error(`[nuxt] Await expressions are not supported in definePageMeta. File: '${id}'`) logger.error(`Await expressions are not supported in definePageMeta. File: '${id}'`)
throw new Error('await in definePageMeta') throw new Error('await in definePageMeta')
} }
if ( if (

View File

@ -2,7 +2,7 @@ import { runInNewContext } from 'node:vm'
import fs from 'node:fs' import fs from 'node:fs'
import { extname, normalize, relative, resolve } from 'pathe' import { extname, normalize, relative, resolve } from 'pathe'
import { encodePath, joinURL, withLeadingSlash } from 'ufo' import { encodePath, joinURL, withLeadingSlash } from 'ufo'
import { logger, resolveFiles, resolvePath, useNuxt } from '@nuxt/kit' import { resolveFiles, resolvePath, useNuxt } from '@nuxt/kit'
import { genArrayFromRaw, genDynamicImport, genImport, genSafeVariableName } from 'knitwork' import { genArrayFromRaw, genDynamicImport, genImport, genSafeVariableName } from 'knitwork'
import escapeRE from 'escape-string-regexp' import escapeRE from 'escape-string-regexp'
import { filename } from 'pathe/utils' import { filename } from 'pathe/utils'
@ -13,7 +13,7 @@ import type { NuxtPage } from 'nuxt/schema'
import { parseAndWalk } from '../core/utils/parse' import { parseAndWalk } from '../core/utils/parse'
import { getLoader, uniqueBy } from '../core/utils' import { getLoader, uniqueBy } from '../core/utils'
import { toArray } from '../utils' import { logger, toArray } from '../utils'
enum SegmentParserState { enum SegmentParserState {
initial, initial,
@ -252,7 +252,7 @@ export async function getRouteMeta (contents: string, absolutePath: string, extr
try { try {
extractedMeta[key] = JSON.parse(runInNewContext(`JSON.stringify(${valueString})`, {})) extractedMeta[key] = JSON.parse(runInNewContext(`JSON.stringify(${valueString})`, {}))
} catch { } catch {
console.debug(`[nuxt] Skipping extraction of \`${key}\` metadata as it is not JSON-serializable (reading \`${absolutePath}\`).`) logger.debug(`Skipping extraction of \`${key}\` metadata as it is not JSON-serializable (reading \`${absolutePath}\`).`)
dynamicProperties.add(key) dynamicProperties.add(key)
continue continue
} }
@ -265,7 +265,7 @@ export async function getRouteMeta (contents: string, absolutePath: string, extr
continue continue
} }
if (element.type !== 'Literal' || typeof element.value !== 'string') { if (element.type !== 'Literal' || typeof element.value !== 'string') {
console.debug(`[nuxt] Skipping extraction of \`${key}\` metadata as it is not an array of string literals (reading \`${absolutePath}\`).`) logger.debug(`Skipping extraction of \`${key}\` metadata as it is not an array of string literals (reading \`${absolutePath}\`).`)
dynamicProperties.add(key) dynamicProperties.add(key)
continue continue
} }
@ -276,7 +276,7 @@ export async function getRouteMeta (contents: string, absolutePath: string, extr
} }
if (property.value.type !== 'Literal' || (typeof property.value.value !== 'string' && typeof property.value.value !== 'boolean')) { if (property.value.type !== 'Literal' || (typeof property.value.value !== 'string' && typeof property.value.value !== 'boolean')) {
console.debug(`[nuxt] Skipping extraction of \`${key}\` metadata as it is not a string literal or array of string literals (reading \`${absolutePath}\`).`) logger.debug(`Skipping extraction of \`${key}\` metadata as it is not a string literal or array of string literals (reading \`${absolutePath}\`).`)
dynamicProperties.add(key) dynamicProperties.add(key)
continue continue
} }

View File

@ -1,4 +1,5 @@
import { promises as fsp } from 'node:fs' import { promises as fsp } from 'node:fs'
import { useLogger } from '@nuxt/kit'
/** @since 3.9.0 */ /** @since 3.9.0 */
export function toArray<T> (value: T | T[]): T[] { export function toArray<T> (value: T | T[]): T[] {
@ -8,3 +9,5 @@ export function toArray<T> (value: T | T[]): T[] {
export async function isDirectory (path: string) { export async function isDirectory (path: string) {
return (await fsp.lstat(path)).isDirectory() return (await fsp.lstat(path)).isDirectory()
} }
export const logger = useLogger('nuxt')

View File

@ -1,5 +1,6 @@
import { fileURLToPath } from 'node:url' import { fileURLToPath } from 'node:url'
import { resolve } from 'pathe' import { resolve } from 'pathe'
import { consola } from 'consola'
import { expect, it, vi } from 'vitest' import { expect, it, vi } from 'vitest'
import type { ComponentsDir } from 'nuxt/schema' import type { ComponentsDir } from 'nuxt/schema'
@ -10,6 +11,7 @@ const rFixture = (...p: string[]) => resolve(fixtureDir, ...p)
vi.mock('@nuxt/kit', () => ({ vi.mock('@nuxt/kit', () => ({
isIgnored: () => false, isIgnored: () => false,
useLogger: () => consola.create({}).withTag('nuxt'),
})) }))
const dirs: ComponentsDir[] = [ const dirs: ComponentsDir[] = [