From 2bf9028f7e07a86b71e41c193c17b370c05c5d8b Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Tue, 19 Sep 2023 23:26:15 +0200 Subject: [PATCH] refactor(kit,nuxt,schema): use `consola` and improve test dx (#23302) --- .eslintrc | 8 +++++- packages/kit/src/components.ts | 3 +- packages/kit/src/internal/template.ts | 3 +- packages/kit/src/module/install.ts | 3 +- packages/kit/src/pages.ts | 3 +- packages/kit/src/plugin.ts | 3 +- packages/nuxt/src/components/loader.ts | 3 +- packages/nuxt/src/components/module.ts | 6 ++-- packages/nuxt/src/components/scan.ts | 8 +++--- packages/nuxt/src/core/app.ts | 8 +++--- packages/nuxt/src/core/builder.ts | 8 ++++-- .../nuxt/src/core/external-config-files.ts | 6 ++-- packages/nuxt/src/core/nitro.ts | 2 +- packages/nuxt/src/core/nuxt.ts | 4 +-- .../nuxt/src/core/plugins/plugin-metadata.ts | 11 +++---- .../src/core/plugins/resolve-deep-imports.ts | 4 +-- packages/nuxt/src/core/schema.ts | 8 +++--- packages/nuxt/src/imports/module.ts | 4 +-- packages/nuxt/src/pages/module.ts | 10 +++---- packages/nuxt/src/pages/plugins/page-meta.ts | 3 +- .../nuxt/src/pages/runtime/composables.ts | 3 +- packages/nuxt/src/pages/utils.ts | 4 +-- .../treeshake-client.test.ts.snap | Bin 7165 -> 7449 bytes packages/nuxt/test/auto-imports.test.ts | 3 +- .../components/client/WithClientOnlySetup.vue | 10 +++++-- packages/schema/package.json | 1 + packages/schema/src/config/build.ts | 3 +- packages/schema/src/config/vite.ts | 3 +- packages/vite/src/dev-bundler.ts | 2 +- .../vite/src/runtime/vite-node-shared.mjs | 1 + packages/vite/src/runtime/vite-node.mjs | 3 +- pnpm-lock.yaml | 7 +++++ scripts/bump-edge.ts | 3 +- scripts/bump-rc.ts | 3 +- scripts/bump.ts | 3 +- scripts/crawl.mjs | 2 ++ scripts/update-changelog.ts | 3 +- .../basic-types/components/WithTypes.vue | 1 + .../basic/components/ClientWrapped.client.vue | 4 ++- test/fixtures/basic/layouts/custom-async.vue | 4 ++- test/fixtures/basic/pages/async-parent.vue | 4 ++- .../basic/pages/async-parent/child.vue | 4 ++- .../pages/fixed-keyed-child-parent/[foo].vue | 4 ++- .../basic/pages/keyed-child-parent/[foo].vue | 4 ++- .../basic/pages/keyed-composables/index.vue | 16 ++++++++--- .../basic/pages/navigate-to-error.vue | 4 ++- .../basic/pages/navigate-to-redirect.vue | 4 ++- .../basic/pages/nuxt-link/trailing-slash.vue | 7 +++-- .../basic/pages/suspense/async-[parent].vue | 8 ++++-- .../suspense/async-[parent]/async-[child].vue | 8 ++++-- .../suspense/async-[parent]/sync-[child].vue | 4 ++- .../basic/pages/suspense/sync-[parent].vue | 4 ++- .../suspense/sync-[parent]/async-[child].vue | 8 ++++-- .../suspense/sync-[parent]/sync-[child].vue | 4 ++- test/fixtures/basic/pages/with-layout2.vue | 4 ++- test/fixtures/basic/plugins/chunk-error.ts | 4 ++- test/fixtures/minimal/app.vue | 5 +++- test/setup-env.ts | 27 ++++++++++++++++++ test/utils.ts | 6 +++- vitest.config.ts | 1 + 60 files changed, 215 insertions(+), 86 deletions(-) create mode 100644 test/setup-env.ts diff --git a/.eslintrc b/.eslintrc index 8cc17845b5..528bcc4a57 100644 --- a/.eslintrc +++ b/.eslintrc @@ -26,7 +26,7 @@ ], "no-only-tests/no-only-tests": "error", "unicorn/prefer-node-protocol": "error", - "no-console": "off", + "no-console": "warn", "vue/multi-word-component-names": "off", "vue/one-component-per-file": "off", "vue/require-default-prop": "off", @@ -120,6 +120,12 @@ } ] } + }, + { + "files": ["packages/nuxt/src/app/**", "test/**", "**/runtime/**"], + "rules": { + "no-console": "off" + } } ], "settings": { diff --git a/packages/kit/src/components.ts b/packages/kit/src/components.ts index 294714d273..e344b7a95a 100644 --- a/packages/kit/src/components.ts +++ b/packages/kit/src/components.ts @@ -2,6 +2,7 @@ import { kebabCase, pascalCase } from 'scule' import type { Component, ComponentsDir } from '@nuxt/schema' import { useNuxt } from './context' import { assertNuxtCompatibility } from './compatibility' +import { logger } from './logger' /** * Register a directory to be scanned for components and imported only when used. @@ -57,7 +58,7 @@ export async function addComponent (opts: AddComponentOptions) { // but we warn if they are equal. if (newPriority === existingPriority) { const name = existingComponent.pascalName || existingComponent.kebabName - console.warn(`Overriding ${name} component. You can specify a \`priority\` option when calling \`addComponent\` to avoid this warning.`) + logger.warn(`Overriding ${name} component. You can specify a \`priority\` option when calling \`addComponent\` to avoid this warning.`) } Object.assign(existingComponent, component) } else { diff --git a/packages/kit/src/internal/template.ts b/packages/kit/src/internal/template.ts index 8672429638..f5024b52db 100644 --- a/packages/kit/src/internal/template.ts +++ b/packages/kit/src/internal/template.ts @@ -4,6 +4,7 @@ import { template as lodashTemplate } from 'lodash-es' import { genDynamicImport, genImport, genSafeVariableName } from 'knitwork' import type { NuxtTemplate } from '@nuxt/schema' +import { logger } from '../logger' /** @deprecated */ // TODO: Remove support for compiling ejs templates in v4 @@ -14,7 +15,7 @@ export async function compileTemplate (template: NuxtTemplate, ctx: any) { const srcContents = await fsp.readFile(template.src, 'utf-8') return lodashTemplate(srcContents, {})(data) } catch (err) { - console.error('Error compiling template: ', template) + logger.error('Error compiling template: ', template) throw err } } diff --git a/packages/kit/src/module/install.ts b/packages/kit/src/module/install.ts index 93d76f1595..8d08e80e28 100644 --- a/packages/kit/src/module/install.ts +++ b/packages/kit/src/module/install.ts @@ -7,6 +7,7 @@ import { useNuxt } from '../context' import { requireModule } from '../internal/cjs' import { importModule } from '../internal/esm' import { resolveAlias, resolvePath } from '../resolve' +import { logger } from '../logger' /** Installs a module on a Nuxt instance. */ export async function installModule (moduleToInstall: string | NuxtModule, inlineOptions?: any, nuxt: Nuxt = useNuxt()) { @@ -65,7 +66,7 @@ export async function loadNuxtModuleInstance (nuxtModule: string | NuxtModule, n // Prefer ESM resolution if possible nuxtModule = await importModule(src, nuxt.options.modulesDir).catch(() => null) ?? requireModule(src, { paths: nuxt.options.modulesDir }) } catch (error: unknown) { - console.error(`Error while requiring module \`${nuxtModule}\`: ${error}`) + logger.error(`Error while requiring module \`${nuxtModule}\`: ${error}`) throw error } // nuxt-module-builder generates a module.json with metadata including the version diff --git a/packages/kit/src/pages.ts b/packages/kit/src/pages.ts index 2e9e346ee4..e303c17cf2 100644 --- a/packages/kit/src/pages.ts +++ b/packages/kit/src/pages.ts @@ -3,6 +3,7 @@ import type { NitroRouteConfig } from 'nitropack' import { defu } from 'defu' import { useNuxt } from './context' import { isNuxt2 } from './compatibility' +import { logger } from './logger' export function extendPages (cb: NuxtHooks['pages:extend']) { const nuxt = useNuxt() @@ -54,7 +55,7 @@ export function addRouteMiddleware (input: NuxtMiddleware | NuxtMiddleware[], op if (options.override === true) { app.middleware[find] = middleware } else { - console.warn(`'${middleware.name}' middleware already exists at '${app.middleware[find].path}'. You can set \`override: true\` to replace it.`) + logger.warn(`'${middleware.name}' middleware already exists at '${app.middleware[find].path}'. You can set \`override: true\` to replace it.`) } } else { app.middleware.push(middleware) diff --git a/packages/kit/src/plugin.ts b/packages/kit/src/plugin.ts index 89929c9bed..390219e67c 100644 --- a/packages/kit/src/plugin.ts +++ b/packages/kit/src/plugin.ts @@ -3,6 +3,7 @@ import type { NuxtPlugin, NuxtPluginTemplate } from '@nuxt/schema' import { useNuxt } from './context' import { addTemplate } from './template' import { resolveAlias } from './resolve' +import { logger } from './logger' /** * Normalize a nuxt plugin object @@ -22,7 +23,7 @@ export function normalizePlugin (plugin: NuxtPlugin | string): NuxtPlugin { // TODO: only scan top-level files #18418 const nonTopLevelPlugin = plugin.src.match(/\/plugins\/[^/]+\/index\.[^/]+$/i) if (nonTopLevelPlugin && nonTopLevelPlugin.length > 0 && !useNuxt().options.plugins.find(i => (typeof i === 'string' ? i : i.src).endsWith(nonTopLevelPlugin[0]))) { - console.warn(`[warn] [nuxt] [deprecation] You are using a plugin that is within a subfolder of your plugins directory without adding it to your config explicitly. You can move it to the top-level plugins directory, or include the file '~${nonTopLevelPlugin[0]}' in your plugins config (https://nuxt.com/docs/api/configuration/nuxt-config#plugins-1) to remove this warning.`) + logger.warn(`[deprecation] You are using a plugin that is within a subfolder of your plugins directory without adding it to your config explicitly. You can move it to the top-level plugins directory, or include the file '~${nonTopLevelPlugin[0]}' in your plugins config (https://nuxt.com/docs/api/configuration/nuxt-config#plugins-1) to remove this warning.`) } // Normalize full path to plugin diff --git a/packages/nuxt/src/components/loader.ts b/packages/nuxt/src/components/loader.ts index 46fc264480..b1cea765c6 100644 --- a/packages/nuxt/src/components/loader.ts +++ b/packages/nuxt/src/components/loader.ts @@ -5,6 +5,7 @@ import { pascalCase } from 'scule' import { resolve } from 'pathe' import type { Component, ComponentsOptions } from 'nuxt/schema' +import { logger } from '@nuxt/kit' import { distDir } from '../dirs' import { isVue } from '../core/utils' @@ -54,7 +55,7 @@ export const loaderPlugin = createUnplugin((options: LoaderOptions) => { imports.add(genImport(serverComponentRuntime, [{ name: 'createServerComponent' }])) imports.add(`const ${identifier} = createServerComponent(${JSON.stringify(name)})`) if (!options.experimentalComponentIslands) { - console.warn(`Standalone server components (\`${name}\`) are not yet supported without enabling \`experimental.componentIslands\`.`) + logger.warn(`Standalone server components (\`${name}\`) are not yet supported without enabling \`experimental.componentIslands\`.`) } return identifier } diff --git a/packages/nuxt/src/components/module.ts b/packages/nuxt/src/components/module.ts index 7666723aa9..c2809a798f 100644 --- a/packages/nuxt/src/components/module.ts +++ b/packages/nuxt/src/components/module.ts @@ -1,6 +1,6 @@ import { statSync } from 'node:fs' import { normalize, relative, resolve } from 'pathe' -import { addPluginTemplate, addTemplate, addVitePlugin, addWebpackPlugin, defineNuxtModule, resolveAlias, updateTemplates } from '@nuxt/kit' +import { addPluginTemplate, addTemplate, addVitePlugin, addWebpackPlugin, defineNuxtModule, logger, resolveAlias, updateTemplates } from '@nuxt/kit' import type { Component, ComponentsDir, ComponentsOptions } from 'nuxt/schema' import { distDir } from '../dirs' @@ -86,7 +86,7 @@ export default defineNuxtModule({ const present = isDirectory(dirPath) if (!present && !DEFAULT_COMPONENTS_DIRS_RE.test(dirOptions.path)) { - console.warn('Components directory not found: `' + dirPath + '`') + logger.warn('Components directory not found: `' + dirPath + '`') } return { @@ -156,7 +156,7 @@ export default defineNuxtModule({ const path = resolve(nuxt.options.srcDir, relativePath) if (componentDirs.some(dir => dir.path === path)) { - console.info(`Directory \`${relativePath}/\` ${event === 'addDir' ? 'created' : 'removed'}`) + logger.info(`Directory \`${relativePath}/\` ${event === 'addDir' ? 'created' : 'removed'}`) return nuxt.callHook('restart') } }) diff --git a/packages/nuxt/src/components/scan.ts b/packages/nuxt/src/components/scan.ts index 92ce451003..95a905f97b 100644 --- a/packages/nuxt/src/components/scan.ts +++ b/packages/nuxt/src/components/scan.ts @@ -2,7 +2,7 @@ import { readdir } from 'node:fs/promises' import { basename, dirname, extname, join, relative } from 'pathe' import { globby } from 'globby' import { pascalCase, splitByCase } from 'scule' -import { isIgnored, useNuxt } from '@nuxt/kit' +import { isIgnored, logger, useNuxt } from '@nuxt/kit' // eslint-disable-next-line vue/prefer-import-from-vue import { hyphenate } from '@vue/shared' import { withTrailingSlash } from 'ufo' @@ -44,7 +44,7 @@ export async function scanComponents (dirs: ComponentsDir[], srcDir: string): Pr const nuxt = useNuxt() const original = relative(nuxt.options.srcDir, dir.path) const corrected = relative(nuxt.options.srcDir, join(dirname(dir.path), caseCorrected)) - console.warn(`[nuxt] Components not scanned from \`~/${corrected}\`. Did you mean to name the directory \`~/${original}\` instead?`) + logger.warn(`Components not scanned from \`~/${corrected}\`. Did you mean to name the directory \`~/${original}\` instead?`) continue } } @@ -130,7 +130,7 @@ export async function scanComponents (dirs: ComponentsDir[], srcDir: string): Pr // Ignore files like `~/components/index.vue` which end up not having a name at all if (!componentName) { - console.warn(`[nuxt] Component did not resolve to a file name in \`~/${relative(srcDir, filePath)}\`.`) + logger.warn(`Component did not resolve to a file name in \`~/${relative(srcDir, filePath)}\`.`) continue } @@ -189,7 +189,7 @@ export function resolveComponentName (fileName: string, prefixParts: string[]) { } function warnAboutDuplicateComponent (componentName: string, filePath: string, duplicatePath: string) { - console.warn(`[nuxt] Two component files resolving to the same name \`${componentName}\`:\n` + + logger.warn(`Two component files resolving to the same name \`${componentName}\`:\n` + `\n - ${filePath}` + `\n - ${duplicatePath}` ) diff --git a/packages/nuxt/src/core/app.ts b/packages/nuxt/src/core/app.ts index ad328e2b39..7dbe752b69 100644 --- a/packages/nuxt/src/core/app.ts +++ b/packages/nuxt/src/core/app.ts @@ -1,7 +1,7 @@ import { promises as fsp, mkdirSync, writeFileSync } from 'node:fs' import { dirname, join, resolve } from 'pathe' import { defu } from 'defu' -import { compileTemplate, findPath, normalizePlugin, normalizeTemplate, resolveAlias, resolveFiles, resolvePath, templateUtils, tryResolveModule } from '@nuxt/kit' +import { compileTemplate, findPath, logger, normalizePlugin, normalizeTemplate, resolveAlias, resolveFiles, resolvePath, templateUtils, tryResolveModule } from '@nuxt/kit' import type { Nuxt, NuxtApp, NuxtPlugin, NuxtTemplate, ResolvedNuxtTemplate } from 'nuxt/schema' import * as defaultTemplates from './templates' @@ -43,7 +43,7 @@ export async function generateApp (nuxt: Nuxt, app: NuxtApp, options: { filter?: const fullPath = template.dst || resolve(nuxt.options.buildDir, template.filename!) const mark = performance.mark(fullPath) const contents = await compileTemplate(template, templateContext).catch((e) => { - console.error(`[nuxt] Could not compile template \`${template.filename}\`.`) + logger.error(`Could not compile template \`${template.filename}\`.`) throw e }) @@ -61,7 +61,7 @@ export async function generateApp (nuxt: Nuxt, app: NuxtApp, options: { filter?: const setupTime = perf ? Math.round((perf.duration * 100)) / 100 : 0 // TODO: remove when Node 14 reaches EOL if (nuxt.options.debug || setupTime > 500) { - console.info(`[nuxt] compiled \`${template.filename}\` in ${setupTime}ms`) + logger.info(`Compiled \`${template.filename}\` in ${setupTime}ms`) } if (template.write) { @@ -191,7 +191,7 @@ export async function annotatePlugins (nuxt: Nuxt, plugins: NuxtPlugin[]) { ...plugin }) } catch (e) { - console.warn(`[nuxt] Could not resolve \`${plugin.src}\`.`) + logger.warn(`Could not resolve \`${plugin.src}\`.`) _plugins.push(plugin) } } diff --git a/packages/nuxt/src/core/builder.ts b/packages/nuxt/src/core/builder.ts index 1a106c3094..ffa65a40ac 100644 --- a/packages/nuxt/src/core/builder.ts +++ b/packages/nuxt/src/core/builder.ts @@ -2,7 +2,7 @@ import { pathToFileURL } from 'node:url' import type { EventType } from '@parcel/watcher' import type { FSWatcher } from 'chokidar' import chokidar from 'chokidar' -import { isIgnored, tryResolveModule, useNuxt } from '@nuxt/kit' +import { isIgnored, logger, tryResolveModule, useNuxt } from '@nuxt/kit' import { interopDefault } from 'mlly' import { debounce } from 'perfect-debounce' import { normalize, relative, resolve } from 'pathe' @@ -93,6 +93,7 @@ function createGranularWatcher () { const nuxt = useNuxt() if (nuxt.options.debug) { + // eslint-disable-next-line no-console console.time('[nuxt] builder:chokidar:watch') } @@ -131,6 +132,7 @@ function createGranularWatcher () { watcher.on('ready', () => { pending-- if (nuxt.options.debug && !pending) { + // eslint-disable-next-line no-console console.timeEnd('[nuxt] builder:chokidar:watch') } }) @@ -140,6 +142,7 @@ function createGranularWatcher () { async function createParcelWatcher () { const nuxt = useNuxt() if (nuxt.options.debug) { + // eslint-disable-next-line no-console console.time('[nuxt] builder:parcel:watch') } const watcherPath = await tryResolveModule('@parcel/watcher', [nuxt.options.rootDir, ...nuxt.options.modulesDir]) @@ -162,6 +165,7 @@ async function createParcelWatcher () { }) watcher.then((subscription) => { if (nuxt.options.debug) { + // eslint-disable-next-line no-console console.timeEnd('[nuxt] builder:parcel:watch') } nuxt.hook('close', () => subscription.unsubscribe()) @@ -169,7 +173,7 @@ async function createParcelWatcher () { } return true } - console.warn('[nuxt] falling back to `chokidar-granular` as `@parcel/watcher` cannot be resolved in your project.') + logger.warn('Falling back to `chokidar-granular` as `@parcel/watcher` cannot be resolved in your project.') return false } diff --git a/packages/nuxt/src/core/external-config-files.ts b/packages/nuxt/src/core/external-config-files.ts index 26cc360fa7..4bc9da5b53 100644 --- a/packages/nuxt/src/core/external-config-files.ts +++ b/packages/nuxt/src/core/external-config-files.ts @@ -1,4 +1,4 @@ -import { findPath } from '@nuxt/kit' +import { findPath, logger } from '@nuxt/kit' import { basename } from 'pathe' import { generateApp as _generateApp } from './app' @@ -18,11 +18,11 @@ export async function checkForExternalConfigurationFiles () { const foundOneExternalConfig = warningMessages.length === 1 if (foundOneExternalConfig) { - console.warn(warningMessages[0]) + logger.warn(warningMessages[0]) } else { const warningsAsList = warningMessages.map(message => `- ${message}`).join('\n') const warning = `Found multiple external configuration files: \n\n${warningsAsList}` - console.warn(warning) + logger.warn(warning) } } diff --git a/packages/nuxt/src/core/nitro.ts b/packages/nuxt/src/core/nitro.ts index abe8ce002c..99d66ec649 100644 --- a/packages/nuxt/src/core/nitro.ts +++ b/packages/nuxt/src/core/nitro.ts @@ -421,7 +421,7 @@ function spaLoadingTemplate (nuxt: Nuxt) { } if (nuxt.options.spaLoadingTemplate) { - console.warn(`[nuxt] Could not load custom \`spaLoadingTemplate\` path as it does not exist: \`${nuxt.options.spaLoadingTemplate}\`.`) + logger.warn(`Could not load custom \`spaLoadingTemplate\` path as it does not exist: \`${nuxt.options.spaLoadingTemplate}\`.`) } return '' diff --git a/packages/nuxt/src/core/nuxt.ts b/packages/nuxt/src/core/nuxt.ts index 2f00eb7400..1eba2896ca 100644 --- a/packages/nuxt/src/core/nuxt.ts +++ b/packages/nuxt/src/core/nuxt.ts @@ -389,7 +389,7 @@ async function initNuxt (nuxt: Nuxt) { // Core Nuxt files: app.vue, error.vue and app.config.ts const isFileChange = ['add', 'unlink'].includes(event) if (isFileChange && RESTART_RE.test(path)) { - console.info(`\`${path}\` ${event === 'add' ? 'created' : 'removed'}`) + logger.info(`\`${path}\` ${event === 'add' ? 'created' : 'removed'}`) return nuxt.callHook('restart') } }) @@ -406,7 +406,7 @@ async function initNuxt (nuxt: Nuxt) { // Add prerender payload support const nitro = useNitro() if (nitro.options.static && nuxt.options.experimental.payloadExtraction === undefined) { - console.warn('Using experimental payload extraction for full-static output. You can opt-out by setting `experimental.payloadExtraction` to `false`.') + logger.warn('Using experimental payload extraction for full-static output. You can opt-out by setting `experimental.payloadExtraction` to `false`.') nuxt.options.experimental.payloadExtraction = true } nitro.options.replace['process.env.NUXT_PAYLOAD_EXTRACTION'] = String(!!nuxt.options.experimental.payloadExtraction) diff --git a/packages/nuxt/src/core/plugins/plugin-metadata.ts b/packages/nuxt/src/core/plugins/plugin-metadata.ts index 1cc348ec1e..77aaec22bb 100644 --- a/packages/nuxt/src/core/plugins/plugin-metadata.ts +++ b/packages/nuxt/src/core/plugins/plugin-metadata.ts @@ -9,6 +9,7 @@ import type { Nuxt } from '@nuxt/schema' import { createUnplugin } from 'unplugin' import MagicString from 'magic-string' import { normalize } from 'pathe' +import { logger } from '@nuxt/kit' // eslint-disable-next-line import/no-restricted-paths import type { ObjectPlugin, PluginMeta } from '#app' @@ -122,7 +123,7 @@ export const RemovePluginMetadataPlugin = (nuxt: Nuxt) => createUnplugin(() => { const exports = findExports(code) const defaultExport = exports.find(e => e.type === 'default' || e.name === 'default') if (!defaultExport) { - console.error(`[warn] [nuxt] Plugin \`${plugin.src}\` has no default export and will be ignored at build time. Add \`export default defineNuxtPlugin(() => {})\` to your plugin.`) + logger.warn(`Plugin \`${plugin.src}\` has no default export and will be ignored at build time. Add \`export default defineNuxtPlugin(() => {})\` to your plugin.`) s.overwrite(0, code.length, 'export default () => {}') return { code: s.toString(), @@ -140,7 +141,7 @@ export const RemovePluginMetadataPlugin = (nuxt: Nuxt) => createUnplugin(() => { enter (_node) { if (_node.type === 'ExportDefaultDeclaration' && (_node.declaration.type === 'FunctionDeclaration' || _node.declaration.type === 'ArrowFunctionExpression')) { if ('params' in _node.declaration && _node.declaration.params.length > 1) { - console.warn(`[warn] [nuxt] Plugin \`${plugin.src}\` is in legacy Nuxt 2 format (context, inject) which is likely to be broken and will be ignored.`) + logger.warn(`Plugin \`${plugin.src}\` is in legacy Nuxt 2 format (context, inject) which is likely to be broken and will be ignored.`) s.overwrite(0, code.length, 'export default () => {}') wrapped = true // silence a duplicate error return @@ -155,7 +156,7 @@ export const RemovePluginMetadataPlugin = (nuxt: Nuxt) => createUnplugin(() => { if (node.arguments[0].type !== 'ObjectExpression') { // TODO: Warn if legacy plugin format is detected if ('params' in node.arguments[0] && node.arguments[0].params.length > 1) { - console.warn(`[warn] [nuxt] Plugin \`${plugin.src}\` is in legacy Nuxt 2 format (context, inject) which is likely to be broken and will be ignored.`) + logger.warn(`Plugin \`${plugin.src}\` is in legacy Nuxt 2 format (context, inject) which is likely to be broken and will be ignored.`) s.overwrite(0, code.length, 'export default () => {}') return } @@ -184,12 +185,12 @@ export const RemovePluginMetadataPlugin = (nuxt: Nuxt) => createUnplugin(() => { } }) } catch (e) { - console.error(e) + logger.error(e) return } if (!wrapped) { - console.warn(`[warn] [nuxt] Plugin \`${plugin.src}\` is not wrapped in \`defineNuxtPlugin\`. It is advised to wrap your plugins as in the future this may enable enhancements.`) + logger.warn(`Plugin \`${plugin.src}\` is not wrapped in \`defineNuxtPlugin\`. It is advised to wrap your plugins as in the future this may enable enhancements.`) } if (s.hasChanged()) { diff --git a/packages/nuxt/src/core/plugins/resolve-deep-imports.ts b/packages/nuxt/src/core/plugins/resolve-deep-imports.ts index 032117178e..e97dfd4b5b 100644 --- a/packages/nuxt/src/core/plugins/resolve-deep-imports.ts +++ b/packages/nuxt/src/core/plugins/resolve-deep-imports.ts @@ -1,7 +1,7 @@ import { parseNodeModulePath, resolvePath } from 'mlly' import { isAbsolute, normalize } from 'pathe' import type { Plugin } from 'vite' -import { resolveAlias } from '@nuxt/kit' +import { logger, resolveAlias } from '@nuxt/kit' import type { Nuxt } from '@nuxt/schema' import { pkgDir } from '../../dirs' @@ -23,7 +23,7 @@ export function resolveDeepImportsPlugin (nuxt: Nuxt): Plugin { // TODO: respect nitro runtime conditions conditions: options.ssr ? ['node', 'import', 'require'] : ['import', 'require'] }).catch(() => { - console.log('[nuxt] Could not resolve id', id, importer) + logger.log('Could not resolve id', id, importer) return null }) } diff --git a/packages/nuxt/src/core/schema.ts b/packages/nuxt/src/core/schema.ts index d529427b72..a20e256411 100644 --- a/packages/nuxt/src/core/schema.ts +++ b/packages/nuxt/src/core/schema.ts @@ -6,7 +6,7 @@ import chokidar from 'chokidar' import { interopDefault } from 'mlly' import { defu } from 'defu' import { debounce } from 'perfect-debounce' -import { createResolver, defineNuxtModule, tryResolveModule } from '@nuxt/kit' +import { createResolver, defineNuxtModule, logger, tryResolveModule } from '@nuxt/kit' import { generateTypes, resolveSchema as resolveUntypedSchema @@ -76,7 +76,7 @@ export default defineNuxtModule({ } return } - console.warn('[nuxt] falling back to `chokidar-granular` as `@parcel/watcher` cannot be resolved in your project.') + logger.warn('Falling back to `chokidar-granular` as `@parcel/watcher` cannot be resolved in your project.') } const filesToWatch = await Promise.all(nuxt.options._layers.map(layer => @@ -106,8 +106,8 @@ export default defineNuxtModule({ try { loadedConfig = _resolveSchema(filePath) } catch (err) { - console.warn( - '[nuxt-config-schema] Unable to load schema from', + logger.warn( + 'Unable to load schema from', filePath, err ) diff --git a/packages/nuxt/src/imports/module.ts b/packages/nuxt/src/imports/module.ts index 52a54c16da..dbd51bf226 100644 --- a/packages/nuxt/src/imports/module.ts +++ b/packages/nuxt/src/imports/module.ts @@ -1,4 +1,4 @@ -import { addTemplate, addVitePlugin, addWebpackPlugin, defineNuxtModule, isIgnored, resolveAlias, tryResolveModule, updateTemplates, useNuxt } from '@nuxt/kit' +import { addTemplate, addVitePlugin, addWebpackPlugin, defineNuxtModule, isIgnored, logger, resolveAlias, tryResolveModule, updateTemplates, useNuxt } from '@nuxt/kit' import { isAbsolute, join, normalize, relative, resolve } from 'pathe' import type { Import, Unimport } from 'unimport' import { createUnimport, scanDirExports } from 'unimport' @@ -69,7 +69,7 @@ export default defineNuxtModule>({ const path = resolve(nuxt.options.srcDir, relativePath) if (composablesDirs.includes(path)) { - console.info(`Directory \`${relativePath}/\` ${event === 'addDir' ? 'created' : 'removed'}`) + logger.info(`Directory \`${relativePath}/\` ${event === 'addDir' ? 'created' : 'removed'}`) return nuxt.callHook('restart') } }) diff --git a/packages/nuxt/src/pages/module.ts b/packages/nuxt/src/pages/module.ts index c0ef5a0bc0..0f8756437e 100644 --- a/packages/nuxt/src/pages/module.ts +++ b/packages/nuxt/src/pages/module.ts @@ -1,6 +1,6 @@ import { existsSync, readdirSync } from 'node:fs' import { mkdir, readFile } from 'node:fs/promises' -import { addBuildPlugin, addComponent, addPlugin, addTemplate, addVitePlugin, addWebpackPlugin, defineNuxtModule, findPath, updateTemplates } from '@nuxt/kit' +import { addBuildPlugin, addComponent, addPlugin, addTemplate, addVitePlugin, addWebpackPlugin, defineNuxtModule, findPath, logger, updateTemplates } from '@nuxt/kit' import { dirname, join, relative, resolve } from 'pathe' import { genImport, genObjectFromRawEntries, genString } from 'knitwork' import { joinURL } from 'ufo' @@ -67,7 +67,7 @@ export default defineNuxtModule({ if (restartPaths.some(p => p === path || path.startsWith(p + '/'))) { const newSetting = await isPagesEnabled() if (nuxt.options.pages !== newSetting) { - console.info('Pages', newSetting ? 'enabled' : 'disabled') + logger.info('Pages', newSetting ? 'enabled' : 'disabled') return nuxt.callHook('restart') } } @@ -275,7 +275,7 @@ export default defineNuxtModule({ if (extractedRule) { if (!glob) { const relativePath = relative(nuxt.options.srcDir, path) - console.error(`[nuxt] Could not set inline route rules in \`~/${relativePath}\` as it could not be mapped to a Nitro route.`) + logger.error(`Could not set inline route rules in \`~/${relativePath}\` as it could not be mapped to a Nitro route.`) return } @@ -286,9 +286,9 @@ export default defineNuxtModule({ } catch (e: any) { if (e.toString().includes('Error parsing route rules')) { const relativePath = relative(nuxt.options.srcDir, path) - console.error(`[nuxt] Error parsing route rules within \`~/${relativePath}\`. They should be JSON-serializable.`) + logger.error(`Error parsing route rules within \`~/${relativePath}\`. They should be JSON-serializable.`) } else { - console.error(e) + logger.error(e) } } } diff --git a/packages/nuxt/src/pages/plugins/page-meta.ts b/packages/nuxt/src/pages/plugins/page-meta.ts index 01cce87cf2..07c64ebdf0 100644 --- a/packages/nuxt/src/pages/plugins/page-meta.ts +++ b/packages/nuxt/src/pages/plugins/page-meta.ts @@ -8,6 +8,7 @@ import type { Node } from 'estree-walker' import { walk } from 'estree-walker' import MagicString from 'magic-string' import { isAbsolute } from 'pathe' +import { logger } from '@nuxt/kit' export interface PageMetaPluginOptions { dev?: boolean @@ -90,7 +91,7 @@ export const PageMetaPlugin = createUnplugin((options: PageMetaPluginOptions) => if (!code) { s.append(CODE_EMPTY + (options.dev ? CODE_HMR : '')) const { pathname } = parseURL(decodeURIComponent(pathToFileURL(id).href)) - console.error(`The file \`${pathname}\` is not a valid page as it has no content.`) + logger.error(`The file \`${pathname}\` is not a valid page as it has no content.`) } else { s.overwrite(0, code.length, CODE_EMPTY + (options.dev ? CODE_HMR : '')) } diff --git a/packages/nuxt/src/pages/runtime/composables.ts b/packages/nuxt/src/pages/runtime/composables.ts index 0f189e578b..24714cd252 100644 --- a/packages/nuxt/src/pages/runtime/composables.ts +++ b/packages/nuxt/src/pages/runtime/composables.ts @@ -44,12 +44,13 @@ declare module 'vue-router' { interface RouteMeta extends UnwrapRef {} } -const warnRuntimeUsage = (method: string) => +const warnRuntimeUsage = (method: string) => { console.warn( `${method}() is a compiler-hint helper that is only usable inside ` + 'the script block of a single file component which is also a page. Its arguments should be ' + 'compiled away and passing it at runtime has no effect.' ) +} // eslint-disable-next-line @typescript-eslint/no-unused-vars export const definePageMeta = (meta: PageMeta): void => { diff --git a/packages/nuxt/src/pages/utils.ts b/packages/nuxt/src/pages/utils.ts index ef207aa671..f01586c1f5 100644 --- a/packages/nuxt/src/pages/utils.ts +++ b/packages/nuxt/src/pages/utils.ts @@ -1,7 +1,7 @@ import fs from 'node:fs' import { extname, normalize, relative, resolve } from 'pathe' import { encodePath } from 'ufo' -import { resolveFiles, useNuxt } from '@nuxt/kit' +import { logger, resolveFiles, useNuxt } from '@nuxt/kit' import { genArrayFromRaw, genDynamicImport, genImport, genSafeVariableName } from 'knitwork' import escapeRE from 'escape-string-regexp' import { filename } from 'pathe/utils' @@ -273,7 +273,7 @@ function prepareRoutes (routes: NuxtPage[], parent?: NuxtPage, names = new Set { } } catch (e) { it('should import composables', () => { - console.log(e) + // eslint-disable-next-line no-console + console.error(e) expect(false).toBe(true) }) } diff --git a/packages/nuxt/test/fixture/components/client/WithClientOnlySetup.vue b/packages/nuxt/test/fixture/components/client/WithClientOnlySetup.vue index fdb182b7c1..80a75f7291 100644 --- a/packages/nuxt/test/fixture/components/client/WithClientOnlySetup.vue +++ b/packages/nuxt/test/fixture/components/client/WithClientOnlySetup.vue @@ -107,7 +107,10 @@ const { woooooo, What = isThis } = defineAsyncComponent(async () => { return {} }) -console.log(woooooo) +if (import.meta.client) { + // eslint-disable-next-line no-console + console.log(woooooo) +} const { Deep, assignment: { Pattern = ofComponent } } = defineAsyncComponent(async () => { if (import.meta.client) { @@ -133,7 +136,10 @@ const [Please, { Dont, Doo }, That] = defineAsyncComponent(async () => { return {} }) -console.log(DontRemoveThisSinceItIsUsedInSetup.props) +if (import.meta.client) { + // eslint-disable-next-line no-console + console.log(DontRemoveThisSinceItIsUsedInSetup.props) +}