diff --git a/eslint.config.js b/eslint.config.js index 0512a3023..a1c45bc8e 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -17,4 +17,9 @@ export default createConfigForNuxt({ // TODO: remove usage of `any` throughout codebase '@typescript-eslint/no-explicit-any': 'off', }, +}, { + files: ['src/**'], + rules: { + 'no-console': 'error', + }, }) diff --git a/src/commands/add.ts b/src/commands/add.ts index 3db6bc485..b3ad40aee 100644 --- a/src/commands/add.ts +++ b/src/commands/add.ts @@ -1,7 +1,8 @@ import { existsSync, promises as fsp } from 'node:fs' import { dirname, resolve, extname } from 'pathe' -import { consola } from 'consola' import { defineCommand } from 'citty' + +import { logger } from '../utils/logger' import { loadKit } from '../utils/kit' import { templates } from '../utils/templates' import { cwdArgs, logLevelArgs } from './_shared' @@ -43,7 +44,7 @@ export default defineCommand({ // Validate template name if (!template) { - consola.error( + logger.error( `Template ${templateName} is not supported. Possible values: ${Object.keys( templates, ).join(', ')}`, @@ -53,7 +54,7 @@ export default defineCommand({ // Validate options if (!name) { - consola.error('name argument is missing!') + logger.error('name argument is missing!') process.exit(1) } @@ -66,7 +67,7 @@ export default defineCommand({ // Ensure not overriding user code if (!ctx.args.force && existsSync(res.path)) { - consola.error( + logger.error( `File exists: ${res.path} . Use --force to override or use a different name.`, ) process.exit(1) @@ -75,15 +76,15 @@ export default defineCommand({ // Ensure parent directory exists const parentDir = dirname(res.path) if (!existsSync(parentDir)) { - consola.info('Creating directory', parentDir) + logger.info('Creating directory', parentDir) if (templateName === 'page') { - consola.info('This enables vue-router functionality!') + logger.info('This enables vue-router functionality!') } await fsp.mkdir(parentDir, { recursive: true }) } // Write file await fsp.writeFile(res.path, res.contents.trim() + '\n') - consola.info(`🪄 Generated a new ${templateName} in ${res.path}`) + logger.info(`🪄 Generated a new ${templateName} in ${res.path}`) }, }) diff --git a/src/commands/analyze.ts b/src/commands/analyze.ts index b0150ea7d..8b4be2bd3 100644 --- a/src/commands/analyze.ts +++ b/src/commands/analyze.ts @@ -8,6 +8,7 @@ import { defineCommand } from 'citty' import { loadKit } from '../utils/kit' import { clearDir } from '../utils/fs' import { overrideEnv } from '../utils/env' +import { logger } from '../utils/logger' import { legacyRootDirArgs, dotEnvArgs, cwdArgs, logLevelArgs } from './_shared' export default defineCommand({ @@ -99,10 +100,8 @@ export default defineCommand({ 'utf-8', ) - console.info('Analyze results are available at: `' + analyzeDir + '`') - console.warn( - 'Do not deploy analyze results! Use `nuxi build` before deploying.', - ) + logger.info('Analyze results are available at: `' + analyzeDir + '`') + logger.warn('Do not deploy analyze results! Use `nuxi build` before deploying.') if (ctx.args.serve !== false && !process.env.CI) { const app = createApp() @@ -115,7 +114,7 @@ export default defineCommand({ }) }) - console.info('Starting stats server...') + logger.info('Starting stats server...') app.use('/client', serveFile(join(analyzeDir, 'client.html'))) app.use('/nitro', serveFile(join(analyzeDir, 'nitro.html'))) diff --git a/src/commands/build-module.ts b/src/commands/build-module.ts index 7c1bb63d3..f6561c244 100644 --- a/src/commands/build-module.ts +++ b/src/commands/build-module.ts @@ -1,8 +1,9 @@ import { x } from 'tinyexec' -import { consola } from 'consola' import { resolve } from 'pathe' import { defineCommand } from 'citty' import { readPackageJSON } from 'pkg-types' + +import { logger } from '../utils/logger' import { cwdArgs, legacyRootDirArgs, logLevelArgs } from './_shared' const MODULE_BUILDER_PKG = '@nuxt/module-builder' @@ -45,7 +46,7 @@ export default defineCommand({ let cmd = 'nuxt-module-build' if (!hasLocal) { - consola.warn( + logger.warn( `Cannot find locally installed version of \`${MODULE_BUILDER_PKG}\` (>=0.2.0). Falling back to \`npx ${MODULE_BUILDER_PKG}\``, ) cmd = 'npx' diff --git a/src/commands/build.ts b/src/commands/build.ts index a74918ac6..f5a4b56ed 100644 --- a/src/commands/build.ts +++ b/src/commands/build.ts @@ -1,7 +1,8 @@ import { relative, resolve } from 'pathe' -import { consola } from 'consola' import type { Nitro } from 'nitropack' import { defineCommand } from 'citty' + +import { logger } from '../utils/logger' import { loadKit } from '../utils/kit' import { clearBuildDir } from '../utils/fs' import { overrideEnv } from '../utils/env' @@ -61,7 +62,7 @@ export default defineCommand({ try { // Use ? for backward compatibility for Nuxt <= RC.10 nitro = kit.useNitro?.() - consola.info(`Building for Nitro preset: \`${nitro.options.preset}\``) + logger.info(`Building for Nitro preset: \`${nitro.options.preset}\``) } catch { // @@ -72,7 +73,7 @@ export default defineCommand({ await kit.writeTypes(nuxt) nuxt.hook('build:error', (err) => { - consola.error('Nuxt Build Error:', err) + logger.error('Nuxt Build Error:', err) process.exit(1) }) @@ -80,14 +81,14 @@ export default defineCommand({ if (ctx.args.prerender) { if (!nuxt.options.ssr) { - consola.warn( + logger.warn( 'HTML content not prerendered because `ssr: false` was set. You can read more in `https://nuxt.com/docs/getting-started/deployment#static-hosting`.', ) } // TODO: revisit later if/when nuxt build --prerender will output hybrid const dir = nitro?.options.output.publicDir const publicDir = dir ? relative(process.cwd(), dir) : '.output/public' - consola.success( + logger.success( `You can now deploy \`${publicDir}\` to any static hosting!`, ) } diff --git a/src/commands/dev-child.ts b/src/commands/dev-child.ts index ad2e65ad4..7dcc22ac0 100644 --- a/src/commands/dev-child.ts +++ b/src/commands/dev-child.ts @@ -1,7 +1,8 @@ import { resolve } from 'pathe' -import { consola } from 'consola' import { defineCommand } from 'citty' import { isTest } from 'std-env' + +import { logger } from '../utils/logger' import { overrideEnv } from '../utils/env' import type { NuxtDevContext, NuxtDevIPCMessage } from '../utils/dev' import { createNuxtDevServer } from '../utils/dev' @@ -20,8 +21,6 @@ export default defineCommand({ ...legacyRootDirArgs, }, async run(ctx) { - const logger = consola.withTag('nuxi') - if (!process.send && !isTest) { logger.warn( '`nuxi _dev` is an internal command and should not be used directly. Please use `nuxi dev` instead.', diff --git a/src/commands/dev.ts b/src/commands/dev.ts index 7e3f1c383..be2f3ca23 100644 --- a/src/commands/dev.ts +++ b/src/commands/dev.ts @@ -6,14 +6,12 @@ import { setupDotenv } from 'c12' import type { ParsedArgs } from 'citty' import { defineCommand } from 'citty' import { isBun, isTest } from 'std-env' -import { - getArgs as getListhenArgs, - parseArgs as parseListhenArgs, -} from 'listhen/cli' +import { getArgs as getListhenArgs, parseArgs as parseListhenArgs } from 'listhen/cli' import type { HTTPSOptions, ListenOptions } from 'listhen' import type { NuxtOptions } from '@nuxt/schema' -import { consola } from 'consola' import { createJiti } from 'jiti' + +import { logger } from '../utils/logger' import { showVersions } from '../utils/banner' import { loadKit } from '../utils/kit' import { overrideEnv } from '../utils/env' @@ -213,7 +211,7 @@ async function _startSubprocess(devProxy: DevProxy, rawArgs: string[]) { restart() } else if (message.type === 'nuxt:internal:dev:rejection') { - consola.withTag('nuxi').info(`Restarting Nuxt due to error: \`${message.message}\``) + logger.withTag('nuxi').info(`Restarting Nuxt due to error: \`${message.message}\``) restart() } }) diff --git a/src/commands/devtools.ts b/src/commands/devtools.ts index 0483c5321..97536b2a1 100644 --- a/src/commands/devtools.ts +++ b/src/commands/devtools.ts @@ -2,6 +2,7 @@ import { resolve } from 'pathe' import { x } from 'tinyexec' import { defineCommand } from 'citty' +import { logger } from '../utils/logger' import { cwdArgs, legacyRootDirArgs } from './_shared' export default defineCommand({ @@ -22,7 +23,7 @@ export default defineCommand({ const cwd = resolve(ctx.args.cwd || ctx.args.rootDir) if (!['enable', 'disable'].includes(ctx.args.command)) { - console.error(`Unknown command \`${ctx.args.command}\`.`) + logger.error(`Unknown command \`${ctx.args.command}\`.`) process.exit(1) } diff --git a/src/commands/info.ts b/src/commands/info.ts index 3085742d5..268a40bb1 100644 --- a/src/commands/info.ts +++ b/src/commands/info.ts @@ -13,6 +13,7 @@ import nuxiPkg from '../../package.json' assert { type: 'json' } import { tryResolveNuxt } from '../utils/kit' import { getPackageManagerVersion } from '../utils/packageManagers' +import { logger } from '../utils/logger' import { cwdArgs, legacyRootDirArgs } from './_shared' export default defineCommand({ @@ -97,7 +98,7 @@ export default defineCommand({ BuildModules: await listModules((nuxtConfig as any /* nuxt v2 */).buildModules || []), } - console.log('Working directory:', cwd) + logger.log('Working directory:', cwd) let maxLength = 0 const entries = Object.entries(infoObj).map(([key, val]) => { @@ -120,12 +121,6 @@ export default defineCommand({ .write(infoStr) .then(() => true) .catch(() => false) - const splitter = '------------------------------' - console.log( - `Nuxt project info: ${ - copied ? '(copied to clipboard)' : '' - }\n\n${splitter}\n${infoStr}${splitter}\n`, - ) const isNuxt3 = !isLegacy const isBridge = !isNuxt3 && infoObj.BuildModules.includes('bridge') @@ -138,7 +133,8 @@ export default defineCommand({ `👉 Read documentation: ${(isNuxt3 || isBridge) ? 'https://nuxt.com' : 'https://v2.nuxt.com'}`, ].filter(Boolean).join('\n') - console.log('\n' + log + '\n') + const splitter = '------------------------------' + logger.log(`Nuxt project info: ${copied ? '(copied to clipboard)' : ''}\n\n${splitter}\n${infoStr}${splitter}\n\n${log}\n`) }, }) diff --git a/src/commands/init.ts b/src/commands/init.ts index da2e195d7..59bc4c7f0 100644 --- a/src/commands/init.ts +++ b/src/commands/init.ts @@ -1,12 +1,12 @@ import { downloadTemplate, startShell } from 'giget' import type { DownloadTemplateResult } from 'giget' import { relative, resolve } from 'pathe' -import { consola } from 'consola' import { installDependencies } from 'nypm' import { x } from 'tinyexec' import type { PackageManagerName } from 'nypm' import { defineCommand } from 'citty' +import { logger } from '../utils/logger' import { cwdArgs } from './_shared' const DEFAULT_REGISTRY @@ -68,7 +68,7 @@ export default defineCommand({ const templateName = ctx.args.template || DEFAULT_TEMPLATE_NAME if (typeof templateName !== 'string') { - consola.error('Please specify a template!') + logger.error('Please specify a template!') process.exit(1) } @@ -89,7 +89,7 @@ export default defineCommand({ if (process.env.DEBUG) { throw err } - consola.error((err as Error).toString()) + logger.error((err as Error).toString()) process.exit(1) } @@ -106,7 +106,7 @@ export default defineCommand({ packageManagerArg, ) ? packageManagerArg - : await consola.prompt('Which package manager would you like to use?', { + : await logger.prompt('Which package manager would you like to use?', { type: 'select', options: packageManagerOptions, }) @@ -114,10 +114,10 @@ export default defineCommand({ // Install project dependencies // or skip installation based on the '--no-install' flag if (ctx.args.install === false) { - consola.info('Skipping install dependencies step.') + logger.info('Skipping install dependencies step.') } else { - consola.start('Installing dependencies...') + logger.start('Installing dependencies...') try { await installDependencies({ @@ -132,20 +132,20 @@ export default defineCommand({ if (process.env.DEBUG) { throw err } - consola.error((err as Error).toString()) + logger.error((err as Error).toString()) process.exit(1) } - consola.success('Installation completed.') + logger.success('Installation completed.') } if (ctx.args.gitInit === undefined) { - ctx.args.gitInit = await consola.prompt('Initialize git repository?', { + ctx.args.gitInit = await logger.prompt('Initialize git repository?', { type: 'confirm', }) } if (ctx.args.gitInit) { - consola.info('Initializing git repository...\n') + logger.info('Initializing git repository...\n') try { await x('git', ['init', template.dir], { throwOnError: true, @@ -155,12 +155,12 @@ export default defineCommand({ }) } catch (err) { - consola.warn(`Failed to initialize git repository: ${err}`) + logger.warn(`Failed to initialize git repository: ${err}`) } } // Display next steps - consola.log( + logger.log( `\n✨ Nuxt project has been created with the \`${template.name}\` template. Next steps:`, ) const relativeTemplateDir = relative(process.cwd(), template.dir) || '.' @@ -173,7 +173,7 @@ export default defineCommand({ ].filter(Boolean) for (const step of nextSteps) { - consola.log(` › ${step}`) + logger.log(` › ${step}`) } if (ctx.args.shell) { diff --git a/src/commands/module/add.ts b/src/commands/module/add.ts index edb8d9861..20a1994f0 100644 --- a/src/commands/module/add.ts +++ b/src/commands/module/add.ts @@ -4,7 +4,6 @@ import { join } from 'node:path' import type { FileHandle } from 'node:fs/promises' import { defineCommand } from 'citty' import { resolve } from 'pathe' -import { consola } from 'consola' import { addDependency } from 'nypm' import { joinURL } from 'ufo' import { $fetch } from 'ofetch' @@ -12,6 +11,8 @@ import { satisfies } from 'semver' import { updateConfig } from 'c12/update' import { colors } from 'consola/utils' import { readPackageJSON } from 'pkg-types' + +import { logger } from '../../utils/logger' import { cwdArgs, logLevelArgs } from '../_shared' import { runCommand } from '../../run' import { @@ -66,8 +67,8 @@ export default defineCommand({ const projectPkg = await readPackageJSON(cwd) if (!projectPkg.dependencies?.nuxt && !projectPkg.devDependencies?.nuxt) { - consola.warn(`No \`nuxt\` dependency detected in \`${cwd}\`.`) - const shouldContinue = await consola.prompt( + logger.warn(`No \`nuxt\` dependency detected in \`${cwd}\`.`) + const shouldContinue = await logger.prompt( `Do you want to continue anyway?`, { type: 'confirm', @@ -82,7 +83,7 @@ export default defineCommand({ const maybeResolvedModules = await Promise.all(modules.map(moduleName => resolveModule(moduleName, cwd))) const r = maybeResolvedModules.filter((x: ModuleResolution): x is ResolvedModule => x != null) - consola.info(`Resolved ${r.map(x => x.pkgName).join(', ')}, adding module(s)...`) + logger.info(`Resolved ${r.map(x => x.pkgName).join(', ')}, adding module(s)...`) await addModule(r, { ...ctx.args, cwd }, projectPkg) @@ -97,16 +98,12 @@ async function addModule(r: ResolvedModule[], { skipInstall, skipConfig, cwd, de // Add npm dependency if (!skipInstall) { const isDev = Boolean(projectPkg.devDependencies?.nuxt) || dev - consola.info(`Installing \`${r.map(x => x.pkg).join(', ')}\`${isDev ? ' development' : ''} dep(s)`) + logger.info(`Installing \`${r.map(x => x.pkg).join(', ')}\`${isDev ? ' development' : ''} dep(s)`) const res = await addDependency(r.map(x => x.pkg), { cwd, dev: isDev, installPeerDependencies: true }).catch( (error) => { - consola.error(error) - return consola.prompt( - `Install failed for ${ - r.map(x => colors.cyan(x.pkg)).join(', ') - }. Do you want to continue adding the module(s) to ${ - colors.cyan('nuxt.config') - }?`, + logger.error(error) + return logger.prompt( + `Install failed for ${r.map(x => colors.cyan(x.pkg)).join(', ')}. Do you want to continue adding the module(s) to ${colors.cyan('nuxt.config')}?`, { type: 'confirm', initial: false, @@ -125,7 +122,7 @@ async function addModule(r: ResolvedModule[], { skipInstall, skipConfig, cwd, de cwd, configFile: 'nuxt.config', async onCreate() { - consola.info(`Creating \`nuxt.config.ts\``) + logger.info(`Creating \`nuxt.config.ts\``) return getDefaultNuxtConfig() }, async onUpdate(config) { @@ -134,16 +131,16 @@ async function addModule(r: ResolvedModule[], { skipInstall, skipConfig, cwd, de config.modules = [] } if (config.modules.includes(resolved.pkgName)) { - consola.info(`\`${resolved.pkgName}\` is already in the \`modules\``) + logger.info(`\`${resolved.pkgName}\` is already in the \`modules\``) return } - consola.info(`Adding \`${resolved.pkgName}\` to the \`modules\``) + logger.info(`Adding \`${resolved.pkgName}\` to the \`modules\``) config.modules.push(resolved.pkgName) } }, }).catch((error) => { - consola.error(`Failed to update \`nuxt.config\`: ${error.message}`) - consola.error(`Please manually add \`${r.map(x => x.pkgName).join(', ')}\` to the \`modules\` in \`nuxt.config.ts\``) + logger.error(`Failed to update \`nuxt.config\`: ${error.message}`) + logger.error(`Please manually add \`${r.map(x => x.pkgName).join(', ')}\` to the \`modules\` in \`nuxt.config.ts\``) return null }) } @@ -173,12 +170,12 @@ async function resolveModule(moduleName: string, cwd: string): Promise { - consola.warn('Cannot search in the Nuxt Modules database: ' + err) + logger.warn('Cannot search in the Nuxt Modules database: ' + err) return [] }) @@ -199,10 +196,10 @@ async function resolveModule(moduleName: string, cwd: string): Promise 1 ? 'modules' : 'module' - } matching ${cyan(query)} ${ - nuxtVersion ? `for Nuxt ${cyan(nuxtVersion)}` : '' - }:\n`, + logger.success( + `Found ${results.length} Nuxt ${results.length > 1 ? 'modules' : 'module'} matching ${cyan(query)} ${nuxtVersion ? `for Nuxt ${cyan(nuxtVersion)}` : ''}:\n`, ) for (const foundModule of results) { let maxLength = 0 @@ -111,6 +106,6 @@ async function findModuleByKeywords(query: string, nuxtVersion: string) { + value + '\n' } - console.log(infoStr) + logger.log(infoStr) } } diff --git a/src/commands/prepare.ts b/src/commands/prepare.ts index e0768511b..1099148ea 100644 --- a/src/commands/prepare.ts +++ b/src/commands/prepare.ts @@ -1,7 +1,7 @@ import { relative, resolve } from 'pathe' -import { consola } from 'consola' - import { defineCommand } from 'citty' + +import { logger } from '../utils/logger' import { clearBuildDir } from '../utils/fs' import { loadKit } from '../utils/kit' @@ -42,7 +42,7 @@ export default defineCommand({ await buildNuxt(nuxt) await writeTypes(nuxt) - consola.success( + logger.success( 'Types generated in', relative(process.cwd(), nuxt.options.buildDir), ) diff --git a/src/commands/preview.ts b/src/commands/preview.ts index d88094b45..5dad6edf4 100644 --- a/src/commands/preview.ts +++ b/src/commands/preview.ts @@ -3,9 +3,10 @@ import { dirname, relative } from 'node:path' import { x } from 'tinyexec' import { setupDotenv } from 'c12' import { resolve } from 'pathe' -import { consola } from 'consola' import { box, colors } from 'consola/utils' import { defineCommand } from 'citty' + +import { logger } from '../utils/logger' import { loadKit } from '../utils/kit' import { envNameArgs, legacyRootDirArgs, dotEnvArgs, cwdArgs, logLevelArgs } from './_shared' @@ -44,7 +45,7 @@ export default defineCommand({ const nitroJSONPaths = [resolvedOutputDir, defaultOutput] const nitroJSONPath = nitroJSONPaths.find(p => existsSync(p)) if (!nitroJSONPath) { - consola.error( + logger.error( 'Cannot find `nitro.json`. Did you run `nuxi build` first? Search path:\n', nitroJSONPaths, ) @@ -54,7 +55,7 @@ export default defineCommand({ const nitroJSON = JSON.parse(await fsp.readFile(nitroJSONPath, 'utf-8')) if (!nitroJSON.commands.preview) { - consola.error('Preview is not supported for this build.') + logger.error('Preview is not supported for this build.') process.exit(1) } @@ -65,7 +66,7 @@ export default defineCommand({ ] as const const _infoKeyLen = Math.max(...info.map(([label]) => label.length)) - consola.log( + logger.log( box( [ 'You are running Nuxt production build in preview mode.', @@ -91,15 +92,15 @@ export default defineCommand({ ? existsSync(resolve(cwd, ctx.args.dotenv)) : existsSync(cwd) if (envExists) { - consola.info( + logger.info( `Loading \`${ctx.args.dotenv || '.env'}\`. This will not be loaded when running the server in production.`, ) await setupDotenv({ cwd, fileName: ctx.args.dotenv }) } - consola.info(`Starting preview command: \`${nitroJSON.commands.preview}\``) + logger.info(`Starting preview command: \`${nitroJSON.commands.preview}\``) const [command, ...commandArgs] = nitroJSON.commands.preview.split(' ') - consola.log('') + logger.log('') await x(command, commandArgs, { nodeOptions: { stdio: 'inherit', cwd: outputPath } }) }, }) diff --git a/src/commands/test.ts b/src/commands/test.ts index 0405a60b0..bcbdc877f 100644 --- a/src/commands/test.ts +++ b/src/commands/test.ts @@ -1,6 +1,7 @@ import { resolve } from 'pathe' import { defineCommand } from 'citty' +import { logger } from '../utils/logger' import { cwdArgs, legacyRootDirArgs, logLevelArgs } from './_shared' export default defineCommand({ @@ -55,8 +56,6 @@ async function importTestUtils(): Promise { err = _err } } - console.error(err) - throw new Error( - '`@nuxt/test-utils` seems missing. Run `npm i -D @nuxt/test-utils` or `yarn add -D @nuxt/test-utils` to install.', - ) + logger.error(err) + throw new Error('`@nuxt/test-utils` seems missing. Run `npm i -D @nuxt/test-utils` or `yarn add -D @nuxt/test-utils` to install.') } diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts index a5bb807a4..1c0797eb8 100644 --- a/src/commands/upgrade.ts +++ b/src/commands/upgrade.ts @@ -1,11 +1,12 @@ import { existsSync } from 'node:fs' -import { consola } from 'consola' import { colors } from 'consola/utils' import { resolve } from 'pathe' import type { PackageJson } from 'pkg-types' import { readPackageJSON } from 'pkg-types' import { defineCommand } from 'citty' import { addDependency, detectPackageManager } from 'nypm' + +import { logger } from '../utils/logger' import { getPackageManagerVersion } from '../utils/packageManagers' import { rmRecursive, touchFile } from '../utils/fs' import { cleanupNuxtDirs, nuxtVersionToGitIdentifier } from '../utils/nuxt' @@ -17,7 +18,7 @@ async function getNuxtVersion(path: string): Promise { try { const pkg = await readPackageJSON('nuxt', { url: path }) if (!pkg.version) { - consola.warn('Cannot find any installed Nuxt versions in ', path) + logger.warn('Cannot find any installed Nuxt versions in ', path) } return pkg.version || null } @@ -42,7 +43,7 @@ const nuxtVersionTags = { } async function getNightlyVersion(packageNames: string[]): Promise<{ npmPackages: string[], nuxtVersion: string }> { - const result = await consola.prompt( + const result = await logger.prompt( 'Which nightly Nuxt release channel do you want to install? (3.x or 4.x)', { type: 'select', @@ -93,18 +94,18 @@ export default defineCommand({ // Check package manager const packageManager = await detectPackageManager(cwd) if (!packageManager) { - consola.error( + logger.error( `Unable to determine the package manager used by this project.\n\nNo lock files found in \`${cwd}\`, and no \`packageManager\` field specified in \`package.json\`.\n\nPlease either add the \`packageManager\` field to \`package.json\` or execute the installation command for your package manager. For example, you can use \`pnpm i\`, \`npm i\`, \`bun i\`, or \`yarn i\`, and then try again.`, ) process.exit(1) } const { name: packageManagerName, lockFile: lockFileCandidates } = packageManager const packageManagerVersion = getPackageManagerVersion(packageManagerName) - consola.info('Package manager:', packageManagerName, packageManagerVersion) + logger.info('Package manager:', packageManagerName, packageManagerVersion) // Check currently installed Nuxt version const currentVersion = (await getNuxtVersion(cwd)) || '[unknown]' - consola.info('Current Nuxt version:', currentVersion) + logger.info('Current Nuxt version:', currentVersion) const pkg = await readPackageJSON(cwd).catch(() => null) @@ -129,7 +130,7 @@ export default defineCommand({ .map(p => colors.cyan(p)) .join(' and ') if (ctx.args.force === undefined) { - ctx.args.force = await consola.prompt( + ctx.args.force = await logger.prompt( `Would you like to recreate ${forceRemovals} to fix problems with hoisted dependency versions and ensure you have the most up-to-date dependencies?`, { type: 'confirm', @@ -138,7 +139,7 @@ export default defineCommand({ ) } if (ctx.args.force) { - consola.info( + logger.info( `Recreating ${forceRemovals}. If you encounter any issues, revert the changes and try with \`--no-force\``, ) await rmRecursive(toRemove.map(file => resolve(cwd, file))) @@ -148,7 +149,7 @@ export default defineCommand({ } const versionType = ctx.args.channel === 'nightly' ? 'nightly' : 'latest stable' - consola.info(`Installing ${versionType} Nuxt ${nuxtVersion} release...`) + logger.info(`Installing ${versionType} Nuxt ${nuxtVersion} release...`) await addDependency(npmPackages, { cwd, @@ -170,17 +171,17 @@ export default defineCommand({ // Check installed Nuxt version again const upgradedVersion = (await getNuxtVersion(cwd)) || '[unknown]' - consola.info('Upgraded Nuxt version:', upgradedVersion) + logger.info('Upgraded Nuxt version:', upgradedVersion) if (upgradedVersion === '[unknown]') { return } if (upgradedVersion === currentVersion) { - consola.success('You\'re already using the latest version of Nuxt.') + logger.success('You\'re already using the latest version of Nuxt.') } else { - consola.success( + logger.success( 'Successfully upgraded Nuxt from', currentVersion, 'to', @@ -192,7 +193,7 @@ export default defineCommand({ const commitA = nuxtVersionToGitIdentifier(currentVersion) const commitB = nuxtVersionToGitIdentifier(upgradedVersion) if (commitA && commitB) { - consola.info( + logger.info( 'Changelog:', `https://github.com/nuxt/nuxt/compare/${commitA}...${commitB}`, ) @@ -210,7 +211,7 @@ function normaliseLockFile(cwd: string, lockFiles: string | Array | unde const lockFile = lockFiles?.find(file => existsSync(resolve(cwd, file))) if (lockFile === undefined) { - consola.error(`Unable to find any lock files in ${cwd}`) + logger.error(`Unable to find any lock files in ${cwd}`) return undefined } diff --git a/src/main.ts b/src/main.ts index 6f97dc12a..35630b3bd 100644 --- a/src/main.ts +++ b/src/main.ts @@ -4,6 +4,7 @@ import nuxiPkg from '../package.json' assert { type: 'json' } import { commands } from './commands' import { setupGlobalConsole } from './utils/console' import { checkEngines } from './utils/engines' +import { logger } from './utils/logger' export const main = defineCommand({ meta: { @@ -22,7 +23,7 @@ export const main = defineCommand({ if (command !== '_dev' && provider !== 'stackblitz') { backgroundTasks = Promise.all([ checkEngines(), - ]).catch(err => console.error(err)) + ]).catch(err => logger.error(err)) } // Avoid background check to fix prompt issues diff --git a/src/utils/banner.ts b/src/utils/banner.ts index 06cde526f..9a93d1296 100644 --- a/src/utils/banner.ts +++ b/src/utils/banner.ts @@ -1,5 +1,6 @@ import { colors } from 'consola/utils' import { readPackageJSON } from 'pkg-types' +import { logger } from './logger' export async function showVersions(cwd: string) { const { bold, gray, green } = colors @@ -10,5 +11,5 @@ export async function showVersions(cwd: string) { const nuxtVersion = await getPkgVersion('nuxt') || await getPkgVersion('nuxt-nightly') || await getPkgVersion('nuxt3') || await getPkgVersion('nuxt-edge') const nitroVersion = await getPkgVersion('nitropack') || await getPkgVersion('nitropack-nightly') || await getPkgVersion('nitropack-edge') - console.log(gray(green(`Nuxt ${bold(nuxtVersion)}`) + (nitroVersion ? ` with Nitro ${bold(nitroVersion)}` : ''))) + logger.log(gray(green(`Nuxt ${bold(nuxtVersion)}`) + (nitroVersion ? ` with Nitro ${bold(nitroVersion)}` : ''))) } diff --git a/src/utils/dev.ts b/src/utils/dev.ts index 851706f29..814493f09 100644 --- a/src/utils/dev.ts +++ b/src/utils/dev.ts @@ -4,7 +4,6 @@ import type { AddressInfo } from 'node:net' import { relative, resolve, join } from 'pathe' import chokidar from 'chokidar' import type { FSWatcher } from 'chokidar' -import { consola } from 'consola' import { debounce } from 'perfect-debounce' import { toNodeListener } from 'h3' import { joinURL } from 'ufo' @@ -13,6 +12,8 @@ import { listen } from 'listhen' import type { Nuxt, NuxtConfig } from '@nuxt/schema' import type { Jiti } from 'jiti/lib/types' import { createJiti } from 'jiti' + +import { logger } from '../utils/logger' import { loadKit } from '../utils/kit' import { loadNuxtManifest, writeNuxtManifest } from '../utils/nuxt' import { clearBuildDir } from '../utils/fs' @@ -146,7 +147,7 @@ class NuxtDevServer extends EventEmitter { await this._load(reload, reason) } catch (error) { - consola.error(`Cannot ${reload ? 'restart' : 'start'} nuxt: `, error) + logger.error(`Cannot ${reload ? 'restart' : 'start'} nuxt: `, error) this._handler = undefined this._loadingMessage = 'Error while loading Nuxt. Please check console and fix errors.' @@ -160,7 +161,7 @@ class NuxtDevServer extends EventEmitter { this._handler = undefined this.emit('loading', this._loadingMessage) if (reload) { - consola.info(this._loadingMessage) + logger.info(this._loadingMessage) } if (this._currentNuxt) { @@ -273,12 +274,13 @@ class NuxtDevServer extends EventEmitter { ?.https as boolean | { key: string, cert: string } if (this.listener.https && !process.env.NODE_TLS_REJECT_UNAUTHORIZED) { - consola.warn( + logger.warn( 'You might need `NODE_TLS_REJECT_UNAUTHORIZED=0` environment variable to make https work.', ) } await Promise.all([ + // eslint-disable-next-line no-console kit.writeTypes(this._currentNuxt).catch(console.error), kit.buildNuxt(this._currentNuxt), ]) diff --git a/src/utils/engines.ts b/src/utils/engines.ts index b15184e50..22c52edaa 100644 --- a/src/utils/engines.ts +++ b/src/utils/engines.ts @@ -1,3 +1,5 @@ +import { logger } from './logger' + export async function checkEngines() { const satisfies = await import('semver/functions/satisfies.js').then( r => @@ -7,7 +9,7 @@ export async function checkEngines() { const nodeRange = '>= 18.0.0' if (!satisfies(currentNode, nodeRange)) { - console.warn( + logger.warn( `Current version of Node.js (\`${currentNode}\`) is unsupported and might cause issues.\n Please upgrade to a compatible version \`${nodeRange}\`.`, ) } diff --git a/src/utils/env.ts b/src/utils/env.ts index a8fdeb3dc..2a9f6fe7b 100644 --- a/src/utils/env.ts +++ b/src/utils/env.ts @@ -1,7 +1,9 @@ +import { logger } from './logger' + export const overrideEnv = (targetEnv: string) => { const currentEnv = process.env.NODE_ENV if (currentEnv && currentEnv !== targetEnv) { - console.warn( + logger.warn( `Changing \`NODE_ENV\` from \`${currentEnv}\` to \`${targetEnv}\`, to avoid unintended behavior.`, ) } diff --git a/src/utils/fs.ts b/src/utils/fs.ts index 9960cf6a2..bc7c2273c 100644 --- a/src/utils/fs.ts +++ b/src/utils/fs.ts @@ -1,6 +1,7 @@ import { existsSync, promises as fsp } from 'node:fs' import { join } from 'pathe' -import { consola } from 'consola' + +import { logger } from '../utils/logger' // Check if a file exists async function exists(path: string) { @@ -39,7 +40,7 @@ export async function rmRecursive(paths: string[]) { paths .filter(p => typeof p === 'string') .map(async (path) => { - consola.debug('Removing recursive path', path) + logger.debug('Removing recursive path', path) await fsp.rm(path, { recursive: true, force: true }).catch(() => {}) }), ) @@ -50,6 +51,6 @@ export async function touchFile(path: string) { return } await fsp.writeFile(path, '').catch(() => { - consola.error(`Failed to create file: ${path}`) + logger.error(`Failed to create file: ${path}`) }) } diff --git a/src/utils/logger.ts b/src/utils/logger.ts new file mode 100644 index 000000000..d0d9259e3 --- /dev/null +++ b/src/utils/logger.ts @@ -0,0 +1,3 @@ +import { consola } from 'consola' + +export const logger = consola.withTag('nuxi') diff --git a/src/utils/nuxt.ts b/src/utils/nuxt.ts index bd6ee08c7..d4e77692d 100644 --- a/src/utils/nuxt.ts +++ b/src/utils/nuxt.ts @@ -1,8 +1,9 @@ import { promises as fsp } from 'node:fs' import { dirname, resolve } from 'pathe' -import { consola } from 'consola' import { hash } from 'ohash' import type { Nuxt } from '@nuxt/schema' + +import { logger } from '../utils/logger' import { rmRecursive } from './fs' interface NuxtProjectManifest { @@ -16,7 +17,7 @@ interface NuxtProjectManifest { } export async function cleanupNuxtDirs(rootDir: string, buildDir: string) { - consola.info('Cleaning up generated Nuxt files and caches...') + logger.info('Cleaning up generated Nuxt files and caches...') await rmRecursive( [